Angular 2中的Spring响应为空

问题描述 投票:-1回答:1

我有一个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);
      });
  }

春天代码:

@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);            
}

enter image description here

angular spring-boot
1个回答
0
投票

解决方案由@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);
      });
  }
© www.soinside.com 2019 - 2024. All rights reserved.