在做項目時,用到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() })
結果就可以啦。
