解决前后端分离的跨域请求
1、SpringBoot后端配置一站式解决法~
/** * @ClassName MyWebConfigurer * @Description TODO * @date 2020/10/24 15:57 * @created by ZeyFra */ @SpringBootConfiguration public class MyWebConfiguration implements WebMvcConfigurer { ? // 跨域设置 @Override public void addCorsMappings(CorsRegistry corsRegistry){ corsRegistry.addMapping("/**") .allowCredentials(true) .allowedOrigins("*") .allowedHeaders("*") .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE") .exposedHeaders("access-control-allow-headers","access-control-allow-methods","access-control-allow-origin","access-control-max-age","X-Frame-Options") .maxAge(3600); } ? }
2、Vue&Axios:修改vue.config.js
module.exports = { devServer: { open: true, host: ‘localhost‘, port: 8080, https: false, //以上的ip和端口是我们本机的;下面为需要跨域的 proxy: { //配置跨域 ‘/api‘: { target: ‘http://localhost:5001/api/‘, //这里后台的地址模拟的;应该填写你们真实的后台接口 ws: true, changOrigin: true, //允许跨域 pathRewrite: { ‘^/api‘: ‘‘ //请求的时候使用这个api就可以 } } } } }
3、服务器端添加响应头
response.addHeader(‘Access-Control-Allow-Origin:*’);//允许所有来源访问 response.addHeader(‘Access-Control-Allow-Method:POST,GET’);//允许访问的方式
原文:https://www.cnblogs.com/zeyfra/p/13996511.html