首頁  >  文章  >  web前端  >  springboot和element-axios如何實現跨域請求(程式碼)

springboot和element-axios如何實現跨域請求(程式碼)

不言
不言原創
2018-09-14 17:44:133424瀏覽

這篇文章帶給大家的內容是關於springboot和element-axios如何實現跨域請求(程式碼),有一定的參考價值,有需要的朋友可以參考一下,希望對你有所幫助。

1、初始化element專案
  1.1:vue init webpage '專案名稱'
  1.2:npm i element-ui -S
  1.3:在main.js新增

import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(ElementUI)

2、新增axios跨域請求

  在main.js中新增

#
/**
  * 跨域设置
  * @type {AxiosStatic}
  */
  import axios from 'axios'
  Vue.prototype.$axios = axios
  Vue.config.productionTip = false
  axios.defaults.withCredentials = false//这个默认即为false,如果改为true,可以传递session信息,后端要做相应修改来放行,

3、建立頁面

<template>
  <el-button @click="post">发送请求</el-button>
</template>

<script>
  import axios from "axios";
  export default {

    data() {
      return {
        activeIndex2: &#39;1&#39;
      };
    },
    methods: {
      handleSelect(key, keyPath) {
        console.log(key, keyPath);
      },
      post(){
        axios.get(&#39;http://localhost:8080/test&#39;)
          .then(function (response) {
            console.log(response,"已经成功发送请求!");
          })
          .catch(function (error) {
            console.log("请求失败!");
          });
      }


    }
  }
</script>

4、建立springboot專案

4.1新增一個controller類別

#
@Controller
@CrossOrigin
public class TestController {
    @RequestMapping("/test")
    @ResponseBody
    public JsonResponseExt Test(){
        System.out.println("在执行~~~~~~~~~");
        return JsonResponseExt.success("执行");
    }

}

JsonResponseExt是我自己封裝的一個類,你們可以直接回傳一個物件或字串也是可以的
另外,在controller類別裡要加入@CrossOrigin註解,否則前端回傳結果會報錯

你也可以自己封裝一個設定類別例如

@Configurationpublic class CorsConfig  extends WebMvcConfigurerAdapter {

    @Override    public void addCorsMappings(CorsRegistry registry) {
        System.out.println("----------------------");
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                .maxAge(3600);
    }


}

#5、測試結果

相關建議:

axios請求如何跨網域

#vue-cli axios請求與跨網域

以上是springboot和element-axios如何實現跨域請求(程式碼)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn