当前位置:Gxlcms > 数据库问题 > 解决Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight 跨域问题

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

时间:2021-07-01 10:21:17 帮助过:3人阅读

跨域错误
用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 跨域问题

标签:The   for   script   错误   ret   http   UNC   func   fun   

人气教程排行