【问题标题】:HTTP POST from Angular 5 (to get a JWT) returns NULL in the Response来自 Angular 5 的 HTTP POST(获取 JWT)在响应中返回 NULL
【发布时间】:2018-07-24 01:31:10
【问题描述】:

我有一个用 Java 编写的 REST 登录操作(用于服务器端)。也使用JWT (Jason Web Token)

客户端正在使用Angular 5下的HTTP客户端访问/执行REST API

正在执行的是登录 REST 功能(使用 HTTP 客户端)。之后返回信息,返回码状态为200(表示一切正常)。

根据 Chrome 浏览器的“网络”标签,RC 返回 200。此外,令牌位于标头中

即使是这种情况,响应也会设置为 NULL。

代码运行

[ ... snip ...]

return this.http.post(url, JSON.stringify({ username: username, password: password }))
      .map((response: Response) => {

        console.log( "==>  looking for the answer - begin ");
        console.log( response );
        console.log( "==>  looking for the answer - end ");

[ ... snip ...]

在控制台中生成的值

NgForm {submitted: true, _directives: Array(2), ngSubmit: EventEmitter, form: FormGroup}control: (...)controls: (...)dirty: (...)disabled: (...)enabled: (...)errors: (...)form: FormGroup {validator: null, asyncValidator: null, _onCollectionChange: ƒ, pristine: false, touched: true, …}formDirective: (...)invalid: (...)ngSubmit: EventEmitter {_isScalar: false, observers: Array(1), closed: false, isStopped: false, hasError: false, …}path: (...)pending: (...)pristine: (...)status: (...)statusChanges: (...)submitted: truetouched: (...)untouched: (...)valid: (...)value: (...)valueChanges: (...)_directives: (2) [NgModel, NgModel]__proto__: ControlContainer
admin-login.component.ts:72  getting ready to go call the service 
admin-login.component.ts:76  values for id and password terrencedarby ----- 3333333333
admin-services.service.ts:175 ==>  looking for the answer - begin 
admin-services.service.ts:176 null
admin-services.service.ts:177 ==>  looking for the answer - end 

问题: 为什么会这样?

TIA

当前 Angular 版本

Angular CLI: 1.6.8
Node: 8.9.4
OS: win32 x64
Angular: 5.1.1
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

@angular/cli: 1.6.8
@angular-devkit/build-optimizer: 0.0.42
@angular-devkit/core: 0.0.23
@angular-devkit/schematics: 0.0.42
@ngtools/json-schema: 1.1.0
@ngtools/webpack: 1.9.8
@schematics/angular: 0.1.17
typescript: 2.4.2
webpack: 3.10.0

admin-services.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { User } from 'app/pages/auth-admin/_admin-model/user';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';


import { HttpClient, HttpParams } from '@angular/common/http';
import { Services } from '@angular/core/src/view';
import { ImplicitReceiver, componentFactoryName } from '@angular/compiler';
import { not } from '@angular/compiler/src/output/output_ast';

import 'rxjs/add/observable/concat';
import 'rxjs/add/observable/defer';
import 'rxjs/add/observable/empty';
import 'rxjs/add/observable/from';
import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/observable/merge';
import 'rxjs/add/observable/timer';
import 'rxjs/add/operator/concatMap';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/expand';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/first';
import 'rxjs/add/operator/let';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/operator/publishReplay';
import 'rxjs/add/operator/shareReplay';
import 'rxjs/add/operator/reduce';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/share';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/take';
import 'rxjs/add/operator/takeWhile';
import 'rxjs/add/observable/throw';


import * as JWT from 'jwt-decode';
import { Response } from '@angular/http';


export const ANONYMOUS_USER: User = {
  id: undefined
}


[... snip ...]

  adminLogin(username, password): Observable<boolean> {
    let url = `${this._apiRoot}/login`;
    let tokenResp = {};

    return this.http.post(url, JSON.stringify({ username: username, password: password }))
      .map((response: Response) => {

        // login successful if there's a token in the response
        let token = response.json() && response.json().token;

        if (token) {

          let t = JWT(token);

          console.log("-- what is in the token --");
          console.log(t);

          //initiialize
          let setUser: User = ANONYMOUS_USER;

          // need to set the value here
          this.userLoggedIn.next(setUser);

          // store username and jwt token in local storage to keep user logged in between page refreshes
          // => SET BACK: localStorage.setItem('currentUser', JSON.stringify(this.userLoggedIn));
          // => SET BACK: this.userLoggedIn = JSON.parse(localStorage.getItem('currentUser'));

          // return true to indicate successful login
          return true;
        } else {
          // throw an error that the token was "whack"
          return Observable.throw(
            new Error("APX: the token was not set properly"));
        }
        //return response.json();
      })
      .catch(e => {
        console.error(e);

        if (e.status === 401) {
          return Observable.throw(
            new Error("Error Code : 401 - Unauthorized Access To Server "));
        }

        return Observable.throw(
          new Error( "Unexpected Error Code: " + e.status ));
      });
  }
[... snip ...]

【问题讨论】:

  • 我遇到了同样的问题,可能你的问题出在后端,令牌正在返回但没有正文内容。你在使用 Spring Security 吗?如果是,请告诉我您的 TokenAuthenticationService,我可以告诉您发生了什么

标签: angular rest jwt


【解决方案1】:

您需要阅读完整的回复,而不仅仅是正文。请参考HTTP client documentation。你的 post call 应该是这样的:

this.http.post(url, JSON.stringify({ username: username, password: password }), { observe: 'response' })
    .subscribe((response: HttpResponse<any>) => { ... });

【讨论】:

  • 谢谢 试试这个 - 但是 - 没有正文。似乎只有一个标题。也没有 Cookie。但是 - 会尝试这个并用我的结果更新它。
  • HttpResponse 包含您实际响应中的所有数据:标头、正文(如果存在或为空)等。
  • 再次感谢 - 得到响应信息,我在哪里可以找到令牌?
  • 通过 response.headers angular.io/api/common/http/HttpResponse访问标头
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-08
  • 2018-08-15
  • 2019-02-22
  • 2018-05-23
  • 1970-01-01
相关资源
最近更新 更多