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.

如下圖:

 

仔細看看自己跨域配置,設置成這樣:

//設置跨域請求
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()
})

 

結果就可以啦。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM