前言
前后端分离项目不配置跨域就会在前端显示这些
跨域,指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对JavaScript施加的安全限制。
同源是指:域名,协议,端口均相同。
接下来,就要分别配置前后端
我的项目前端是localhost:8080,后端localhost:8443/api
1、前端
1)在项目根目录下创建vue.config.js文件:
内容就是这些,自己改一下对应的地址即可
module.exports = {
devServer: {
overlay: {
// 让浏览器 overlay 同时显示警告和错误
warnings: true,
errors: true
},
host: 'localhost',
port: 8080, // 端口号
https: false, // https:{type:Boolean}
open: true, // 配置自动启动浏览器
hotOnly: true, // 热更新
proxy: {
// 配置多个跨域
'/api': {
target: 'http://localhost:8443',//跨域接口的地址
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
},
headers: {
'Access-Control-Allow-Origin': '*',
}
}
};
2)在main.js设置反向代理
// 设置反向代理,前端请求默认发送到 http://localhost:8443/api
var axios = require('axios')
axios.defaults.baseURL = 'http://localhost:8443/api'
//让前端能够带上 cookie。这样,前端每次发送请求时就会带上 sessionId,shiro 就可以通过 sessionId 获取登录状态并执行是否登录的判断。
axios.defaults.withCredentials = true
// 全局注册,之后可在其他组件中通过 this.$axios 发送数据
Vue.prototype.$axios = axios
2、后端
在配置类中加上这个方法即可
//所有请求都允许跨域
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowCredentials(true) //允许跨域的 cookie
.allowedOrigins("http://localhost:8080")
.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
.allowedHeaders("*");
}
如果只想单个请求跨域,可以在controller的方法上加上注解@CrossOrigin
配置完成后,可以看到跨域请求成功了