![](/img/trans.png)
[英]Upload File Api request works in postman but not in nodejs and react MERN
[英]Authorization request works in Postman but not in React
為了測試我已經部署的后端,我使用了 Postman。 在這里,我使用 email 和密碼測試/auth
端點。 我們使用 JWT 這就是對 Postman 的請求的樣子:
URL : https://<api>/api/auth-service/auth
正文(原始{"email":"jelle@mail.com","password":"test"}
響應是 HTTP 狀態 200 OK, Authorization
header 包含不記名令牌。 但是,當我使用fetch
命令嘗試(似乎)與 React 相同時,它仍然收到 HTTP 狀態 200 OK,但沒有Authorization
header。
static async handleSignIn(email, password) {
let result = null;
await fetch(process.env.REACT_APP_GATEWAY_URL + "/api/auth-service/auth", {
method: 'POST',
body: JSON.stringify({email: email, password: password}),
headers: {
"Content-Type": "application/json",
"accept": "*/*",
"Accept-Encoding": "gzip, deflate, br",
"Connection": "keep-alive",
}
})
.then((response) => {
if (response.headers.get("Authorization") != null) {
result = response.headers.get("Authorization");
}
})
.catch(error => {
console.log(error);
throw new Error(error.message)
});
return result;
}
問題是后端,我忘了公開授權 header。
Access-Control-Expose-Headers: Authorization
在 Java Spring 引導中,您可以這樣做:
@Bean
CorsConfigurationSource corsConfigurationSource() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
final CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addExposedHeader("Authorization");
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("HEAD");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
config.addAllowedMethod("DELETE");
config.addAllowedMethod("PATCH");
source.registerCorsConfiguration("/**", config);
return source;
}
注意:允許所有來源和標頭可能不是 go 執行此操作的最安全方法!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.