Home > Article > Web Front-end > How springboot and element-axios implement cross-domain requests (code)
The content of this article is about how springboot and element-axios implement cross-domain requests (code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
1. Initialize element project
1.1: vue init webpage 'Project name'
1.2: npm i element-ui -S
1.3: In main.js Add
import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' Vue.use(ElementUI)
2. Add axios cross-domain request
Add
/** * 跨域设置 * @type {AxiosStatic} */ import axios from 'axios' Vue.prototype.$axios = axios Vue.config.productionTip = false axios.defaults.withCredentials = false//这个默认即为false,如果改为true,可以传递session信息,后端要做相应修改来放行,# in main.js
##3. Create a page
<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. Create a springboot project
4.1 Add a controller class
@Controller @CrossOrigin public class TestController { @RequestMapping("/test") @ResponseBody public JsonResponseExt Test(){ System.out.println("在执行~~~~~~~~~"); return JsonResponseExt.success("执行"); } }JsonResponseExt is a class encapsulated by myself. You can directly return an object or a string.
In addition, the @CrossOrigin annotation must be added to the controller class, otherwise the front-end return result will report an error
@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, test results
##Related recommendations:
How axios requests cross domainsvue-cli axios requests and cross-domainThe above is the detailed content of How springboot and element-axios implement cross-domain requests (code). For more information, please follow other related articles on the PHP Chinese website!