springboot +element-axios跨域请求
生活随笔
收集整理的這篇文章主要介紹了
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 = axiosVue.config.productionTip = falseaxios.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")@ResponseBodypublic JsonResponseExt Test(){System.out.println("在執行~~~~~~~~~");return JsonResponseExt.success("執行");}}
JsonResponseExt是我自己封裝的一個類,你們可以直接返回一個對象或者字符串也是可以的
另外,在controller類里要添加@CrossOrigin注解,否則前端返回結果會報錯
你也可以自己封裝一個配置類例如
@Configuration public class CorsConfig extends WebMvcConfigurerAdapter {@Overridepublic void addCorsMappings(CorsRegistry registry) {System.out.println("----------------------");registry.addMapping("/**").allowedOrigins("*").allowCredentials(true).allowedMethods("GET", "POST", "DELETE", "PUT").maxAge(3600);}}
5、測試結果
?
轉載于:https://www.cnblogs.com/xiluonanfeng/p/9639341.html
總結
以上是生活随笔為你收集整理的springboot +element-axios跨域请求的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 等你来爱我是什么歌?
- 下一篇: Pandas缺失数据