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

Posted earlybridvic

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了解决Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight 跨域问题相关的知识,希望对你有一定的参考价值。

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

 技术图片

解决方法
1 设置Content-Type类型


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


2 改写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发送请求,数据带不过去的问题

以上是关于解决Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight 跨域问题的主要内容,如果未能解决你的问题,请参考以下文章

Status Code: 431 Request Header Fields Too Large

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

跨域问题,Request header field XXXXX is not allowed by Access-Control-Allow-Headers 的问题

加载资源失败:服务器响应状态为 431 (Request Header Fields Too Large)

angularjs post Request header field Content-Type is not allowed by Access-Control-Allow-Headers in p

axios跨域请求报错:Request header field content-type is not allowed by Access-Control-Allow-Headers in pref