项目中,如果遇到axios跨域请求,这种错误:

Access to XMLHttpRequest at 'http://x.x.x: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", " 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()
})

 当ContentType为application/json,会分两次发送请求。

第一次,先发送method为options的请求到服务器,这个请求会询问服务器支持哪些请求方法(get,post等),支持哪些请求头等服务器的支持情况。

等到这个请求返回后,如果我们准备发送的请求符合服务器规则,那么才会继续发送第二次请求,否则会在console中报错。