用axios向服务器提交请求遇到Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response问题
问题:
Access to XMLHttpRequest at '自己的地址' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.
找了很久一直不知道自己问题出在哪里,后来在网上查找资料之后发现把main.js文件中的请求拦截器这段代码注释之后就可以正常使用了
// 挂载之前为axios设立拦截器
// axios.interceptors.request.use(config => {
// //为请求头对象添加token验证的Authorization字段
// config.headers.Authorization = window.sessionStorage.getItem('token')
// console.log(config)
// //在最后必须return config
// return config
// })
如果请求数据为json格式的 话还需要在main.js里面导入qs
import qs from 'qs'
Vue.prototype.$qs = qs
axios请求格式(json):
this.$axios
.post('login.php', this.$qs.stringify('请求的数据'))
.then(res => {
console.log(res)//成功回调函数
})
.catch(err=> {
console.log(err)//失败回调函数
})