Home HTTP POST from Angular 5 (to get a JWT) returns NULL in the Response
Reply: 1

HTTP POST from Angular 5 (to get a JWT) returns NULL in the Response

Casey Harrils
1#
Casey Harrils Published in 2018-02-13 16:03:54Z

I have a REST Login Operation that has been written in Java (for the server side). JWT (Jason Web Token) is also used.

The client side is using the HTTP client under Angular 5 to access / execute the REST API.

What is taking place is that the Login REST functionality (using HTTP client) is executed. Afterwards, information is returned and the Return Code Status is 200 (meaning everything is OK).

According to the Chrome Browser "Network" tab, the RC comes back with a 200. Also, the token is in the header

Even though this is the case, the Response is set to NULL.

code ran

[ ... 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 ...]

values produced in Console

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 

QUESTION: Why is this the case?

TIA

Current Angular Version

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 ...]
VagrantAI
2#
VagrantAI Reply to 2018-02-13 16:09:16Z

You need to read the full response, not just body. Please refer to HTTP client documentation. Your post call should be like that:

this.http.post(url, JSON.stringify({ username: username, password: password }), { observe: 'response' })
    .subscribe((response: HttpResponse<any>) => { ... });
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.397739 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO