項目中,如果遇到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中報錯。