I created my first REST API in Spring Boot and used JWT token. When I send a POST request to my API, I get status OK and in the browser network option I can see a header with JWT token like on the picture.
But I don't know how to get this token from the Response Headers and save it in for example local storage. I was trying a lot of things, but nothing works.
This is my POST request:
fetch('http://localhost:8080/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: 'linda',
password: 'password'
})
});
I created my first REST API in Spring Boot and used JWT token. When I send a POST request to my API, I get status OK and in the browser network option I can see a header with JWT token like on the picture.
But I don't know how to get this token from the Response Headers and save it in for example local storage. I was trying a lot of things, but nothing works.
This is my POST request:
fetch('http://localhost:8080/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: 'linda',
password: 'password'
})
});
Share
Improve this question
edited Jan 15, 2021 at 20:56
Zsolt Meszaros
23.2k19 gold badges58 silver badges69 bronze badges
asked Jan 15, 2021 at 19:00
NiejadekNiejadek
631 silver badge6 bronze badges
1
- 1 Just to note, it's a standard practice to return Bearer token in the response body and not in the headers. It totally makes sense if you have no control over it (skip the next part of my ment), but if you have control over it, I would refactor your solution to use response body. It would also eliminate your question. – skryvets Commented Jan 16, 2021 at 0:00
2 Answers
Reset to default 3There is soultion if someone has the same problem. You have to add to ur config class this bean:
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
configuration.setAllowedHeaders(Arrays.asList("Authorization", "content-type", "x-auth-token"));
configuration.setExposedHeaders(Arrays.asList("x-auth-token","Authorization"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
You'll have to use response.headers
fetch('http://localhost:8080/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: 'linda',
password: 'password'
})
}).then(response => {
console.log(response.headers.get('Authorization'))
});
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744987078a4604674.html
评论列表(0条)