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

Posted joyco773

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了axios跨域请求报错:Request header field content-type is not allowed by Access-Control-Allow-Headers in pref相关的知识,希望对你有一定的参考价值。

在做项目时,用到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(‘*‘, function (req, res, next) 
  //设置请求头
  //允许所有来源访问
  res.header(‘Access-Control-Allow-Origin‘, ‘*‘)
  //用于判断request来自ajax还是传统请求
  res.header("Access-Control-Allow-Headers", " Origin, X-Requested-With, Content-Type, Accept");
  //允许访问的方式
  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()
)

 

结果就可以啦。

以上是关于axios跨域请求报错:Request header field content-type is not allowed by Access-Control-Allow-Headers in pref的主要内容,如果未能解决你的问题,请参考以下文章

axios03-解决请求头兼容导致跨域报错问题

vuejs axios实现跨域http请求接口

Vue--封装axios跨域

Vue--axios:vue中的ajax异步请求(发送和请求数据)vue-resource异步请求和跨域

axios跨域问题

axios上传文件错误:Current request is not a multipart request