记一次vue 使用axios跨域问题(CROS)
在前端框架需要添加Token到请求头中时会出现跨域
前端在axios中配置请求头
// An highlighted block
axios.defaults.headers.common['Authorization'] = 'aaa111222';
// 创建axios实例
const service = axios.create({
// axios中请求配置有baseURL选项,表示请求URL公共部分
baseURL: process.env.VUE_APP_BASE_API,
// 超时
timeout: 10000
})
service.interceptors.request.use(config => {
// 是否需要设置 token
const isToken = (config.headers || {}).isToken === false
if (getToken() && !isToken) {
config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
config.headers['Content-Type'] = 'application/json;charset=utf-8'
}
return config
}, error => {
console.log(error)
Promise.reject(error)
})
后端设置支持跨域请求头token字段
response.setHeader("Access-Control-Allow-Origin","*");
response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE,HEAD,PUT,PATCH");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, token,Authorization");
以nodejs为例,后端解决跨域
app.all("*",function(req,res,next){
//设置允许跨域的域名,*代表允许任意域名跨域
res.header("Access-Control-Allow-Origin","*");
//允许的header类型
res.header("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, token, Authorization");
//跨域允许的请求方式
res.header("Access-Control-Allow-Methods","DELETE,PUT,POST,GET,OPTIONS");
if (req.method.toLowerCase() === 'options')
res.send(200); //让options尝试请求快速结束
else
next();
});