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

在做项目时,用到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.

如下图:

axios跨域请求报错: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 preflight response.

上一篇:Luogu P2015 二叉苹果树


下一篇:《程序设计与算法(二)算法基础》《第二周 递归》放苹果 1664