如何解決vue-resource中出現的Failed to load http://localhost:8000/index: Request header field content-type is not allowed by Access-Control-Allow-Headers in pr ...
如何解決vue-resource中出現的Failed to load http://localhost:8000/index: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response。
問題描述:
在配置伺服器時設置res.header("Access-Control-Allow-Headers", "X-Requested-With")
在vue中發送請求:
結果執行後發現:
意思是:請求標題欄位Content-Type在預檢響應中不被Access-Control-Allow-Headers所允許
經過反覆的測試後,發現瀏覽器是會先發一次options請求,如果請求通過,則繼續發送正式的post請求,而如果不通過則返回以上錯誤
解決辦法:在伺服器配置header,代碼如下
1 app.all('*', function(req, res, next) { 2 res.header("Access-Control-Allow-Origin", "*"); 3 res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Connection, User-Agent, Cookie"); 4 res.header("Access-Control-Allow-Methods", "POST,GET"); 5 res.header("X-Powered-By", ' 3.2.1') 6 res.header("Content-Type", "application/json;charset=utf-8"); 7 next(); 8 })
上面的代碼加入允許的header後,再在vue中發送請求就能正常執行了