解決Axios發送Ajax請求獲取不到Header響應頭裏的Token

問題描述

在做登錄功能的時候 調用登錄接口 想獲取Header裏的Token 然而發現裏面並沒有Token:
在這裏插入圖片描述
在用Postman測試的時候發現是正常的:
在這裏插入圖片描述

原因

瀏覽器默認只能訪問以下幾種響應頭:

  • Cache-Control
  • Content-Length
  • Content-Type
  • Expires
  • Pragma

若想讓瀏覽器能訪問到其它響應頭 則需在服務器上設置Access-Control-Expose-Headers
其值爲要被訪問的響應頭的屬性名

解決方法

在攔截器裏進行配置 添加響應頭

public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    ...
    
    @Override
    protected void successfulAuthentication(HttpServletRequest request,HttpServletResponse response,FilterChain chain,Authentication authResult) throws IOException {
       
        ...

        // 讓瀏覽器能訪問到其它響應頭
        response.addHeader("Access-Control-Expose-Headers","token");

        ...
    }
    
    ...
    
}

成功拿到token:
在這裏插入圖片描述


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章