1. 程式人生 > 實用技巧 >node服務端設定跨域,以及為什麼服務端設定了跨域,還是報跨域錯誤

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,並且手殘的設定了 withCredentials: true

,意思是客戶端想要攜帶驗證資訊頭,但是我的服務端設定是 'supportsCredentials' => false, ,表示不允許攜帶資訊頭,好了,錯誤找到了。

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