解决Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight 跨域问题

跨域错误
用axios.post发送请求的时候出现以下错误

 

错误原因

Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight

解决方法
方法一: 设置Content-Type类型

axios.post('url',{
data
},{
headers: {'Content-Type': 'application/x-www-form-urlencoded'} //加上这个
})

方法二: 改写axios
在<script></script>里增加以下代码

var HTTP = axios.create({
baseURL:'http://localhost:8081/', //这是基础url
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: [function (data) {
// Do whatever you want to transform the data
let ret = ''
for (let it in data) {
ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
}
return ret
}]
});

使用:axios.post改为HTTP.post,例如

HTTP.post('admin/user/login.action',{
name:'test',password:111
})
.then(function(response){
console.log(response.data);
});

备注:这个方式还可以解决用axios发送请求,数据带不过去的问题

posted @ 2019-10-22 14:36  一粒叶子  阅读(2449)  评论(0)    收藏  举报