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

编程知识 更新时间:2023-04-05 07:08:07

跨域错误

用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-Heade

本文发布于:2023-04-05 07:08:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/ca5e4eed3ab58d58f1676decd0e7516f.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Content   Type   field   Request   header

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 45454文章数
  • 14阅读数
  • 0评论数