我有一个Spring API,它在标题中返回一个Authorization Bearer令牌。我可以通过浏览器工具在响应头中看到令牌。但是,Angular将响应记录为null。如何访问此标题,以便我可以通过客户端将其保存在localStorage中?
角色代码:
public login(): Promise<any> {
const user = {
username: 'myusername',
password: 'mypass'
};
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
return this.http.post('http://localhost:8080/login', user, httpOptions)
.toPromise()
.then(res => {
console.log(res); // Returns null
return res;
})
.catch(err => {
console.log(err);
});
}
Spring代码:
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
Authentication authResult) throws IOException, ServletException {
String token = Jwts.builder()
.setSubject(((User) authResult.getPrincipal()).getUsername())
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
.signWith(SignatureAlgorithm.HS512, SECRET.getBytes())
.compact();
response.addHeader(HEADER_STRING, TOKEN_PREFIX + token);
}
答案 0 :(得分:1)
@jonrsharpe提供的解决方案
public login(): Observable<any> {
const user = {
username: 'username',
password: 'password'
};
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
return this.http.post('http://localhost:8080/login', user, {
headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
observe: 'response'
});
}
或
public login(): Promise<any> {
const user = {
username: 'username',
password: 'password'
};
const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
return this.http.post('http://localhost:8080/login', user, {
headers: new HttpHeaders({ 'Content-Type': 'application/json' }), observe: 'response'
})
.toPromise()
.then(results => {
console.log(results);
})
.catch(err => {
console.log(err);
});
}