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: '1'
      };
    },
    methods: {
      handleSelect(key, keyPath) {
        console.log(key, keyPath);
      },
      post(){
        axios.get('http://localhost:8080/test')
          .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注解,否則前端返回結果會報錯

   你也可以自己封裝一個配置類例如

@Configuration
public 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、測試結果

 

 
       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM