[英]Why does the Authorization header token does not get displayed in my browser
我想創建一個登錄系統。 我有一個 Spring Boot Api 和一個 JWT-Token,用於安全性是用本教程編寫的。 在我的前端,我使用 React JS 和 Axios 進行請求。
這是我的 axios 配置:
import axios from 'axios';
const api = axios.create({
baseURL:'http://localhost:8080',
headers: {'Access-Control-Allow-Origin': '*'}
});
export default api;
這是登錄 function:
loginClickHandler = () => {
const data = {
"username":this.state.username,
"password":this.state.password
};
api.post("/login",data)
.then(response => {
console.log(response);
if(response.data !== null) {
this.setState({
loggedIn:true,
userData:response.data
});
}else{
this.showMessage(2,response.data.error)
}
})
.catch(error => {
this.showMessage(2,error);
});
};
登錄 function 本身和其他一切工作正常,但我沒有在瀏覽器中將授權令牌顯示為 header。這是console.log(response)
(僅標題):
headers:
cache-control: "no-cache, no-store, max-age=0, must-revalidate"
content-length: "0"
expires: "0"
pragma: "no-cache"
但是,當我對請求使用 Postman 時,我得到 14 個標頭,其中之一是授權header,其中包含預期的令牌。
現在我的問題是,如何在我的瀏覽器中顯示 header,以便我可以存儲它以供以后請求。
謝謝
編輯:
我剛剛發現授權 Header 顯示在瀏覽器的“網絡”選項卡中,但未顯示在響應中。
解決方案:
我必須在我的JWTAuthenticationFilter successfulAuthentication
方法中添加這一行:
res.addHeader("Access-Control-Expose-Headers",HEADER_STRING);
正如@Jack Chen 和@Sarthak Aggarwal 建議的那樣
您無法在此處的客戶端請求中設置 header 信息:
import axios from 'axios';
const api = axios.create({
baseURL:'http://localhost:8080',
// pass 'Access-Control-Allow-Origin' is not working!
headers: {'Access-Control-Allow-Origin': '*'}
});
export default api;
由於CORS ,在服務器端設置此 header 之前無法獲得正確的響應。 您可以根據本指南在 Spring 引導服務中設置 header。
希望它會有所幫助。
您可能需要在服務器上設置The Access-Control-Expose-Headers
header 設置,因為它允許服務器將允許瀏覽器訪問的標頭列入白名單。`
句法:
Access-Control-Expose-Headers: <header-name>[, <header-name>]*
我有同樣的問題但是使用 NodeJs & Express,
為了解決這個問題,我必須添加這個 expose header:
res.setHeader("Access-Control-Expose-Headers", "<YourHeaderName>");
(與您的解決方案非常相似)
有關 setHeader 方法的更多信息: response.setHeader(name, value)(在 v0.4.0 中添加) https://www.geeksforgeeks.org/node.js-response-setheader-method/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.