node服務端設置跨域,以及為什么服務端設置了跨域,還是報跨域錯誤


拿express舉例

// 配置允許跨域請求;
app.all('*', function(req, res, next) {  
  res.header("Access-Control-Allow-Origin", "http://localhost:3000");  
  res.header("Access-Control-Allow-Credentials", "true");  
  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')  
  res.header("Content-Type", "application/json;charset=utf-8");  
  next();  
});

前后端分離的項目中肯定會碰到跨域的問題,究其原因還是為了安全。我在一個前端工程調試過程中發現,即使我后端已經允許了跨域,但是前端依然報一個跨域錯誤。

the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

 

Access-Control-Allow-Credentials 

這個是服務端下發到客戶端的 response 中頭部字段,意義是允許客戶端攜帶驗證信息,例如 cookie 之類的。這樣客戶端在發起跨域請求的時候,不就可以攜帶允許的頭,還可以攜帶驗證信息的頭,

 

axios 客戶端用axios,並且手殘的設置了 withCredentials: true,意思是客戶端想要攜帶驗證信息頭,但是我的服務端設置是 'supportsCredentials' => false, ,表示不允許攜帶信息頭,好了,錯誤找到了。

我們的客戶端和服務端交互的時候使用的是 token,通過 Authorization頭發送到服務端,並沒有使用到 cookie,所以客戶端沒有必要設置 withCredentials: true


免責聲明!

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



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