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

axios跨域请求报错:Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.,第1张

概述在做项目时,用到axios,数据用post提交时,老是报错,错误提示为: 1 Access to XMLHttpRequest at ‘http://127.0.0.1:3000/api/add‘ from origin ‘http://localhost:8080‘ has been blocked by CORS policy: Request header field content-typ

在做项目时,用到axios,数据用post提交时,老是报错,错误提示为:

1 Access to XMLhttpRequest at ‘http://127.0.0.1:3000/API/add‘ from origin ‘http://localhost:8080‘ has been blocked by CORS policy: Request header fIEld content-type is not allowed by Access-Control-Allow-headers in preflight response.

如下图:

 

仔细看看自己跨域配置,设置成这样:

//设置跨域请求app.all(‘*‘,function (req,res,next) {  //设置请求头  //允许所有来源访问  res.header(‘Access-Control-Allow-Origin‘,‘*‘)  //用于判断request来自AJAX还是传统请求  res.header(‘Access-Control-Allow-headers‘,‘X-Requested-With‘)  //允许访问的方式  res.header(‘Access-Control-Allow-Methods‘,‘PUT,POST,GET,DELETE,OPTIONS‘)  //修改程序信息与版本  res.header(‘X-Powered-By‘,‘ 3.2.1‘)  //内容类型:如果是post请求必须指定这个属性  res.header(‘Content-Type‘,‘application/Json;charset=utf-8‘)  next()})

这是因为我在后端设置跨域请求的时候没有所需的请求类型。于是做了如下修改:

//设置跨域请求app.all(‘*‘,‘*‘)  //用于判断request来自AJAX还是传统请求  res.header("Access-Control-Allow-headers"," Origin,X-Requested-With,Content-Type,Accept");  //允许访问的方式  res.header(‘Access-Control-Allow-Methods‘,‘application/Json;charset=utf-8‘)  next()})

 

结果就可以啦。

总结

以上是内存溢出为你收集整理的axios跨域请求报错:Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.全部内容,希望文章能够帮你解决axios跨域请求报错:Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1015736.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存