2

I am building an angular 6 application that sends a get request to the server through a REST API. The URL takes in a few headers and returns the required data, and has been successfully tested on PostMan. Here is the screenshot showing the headers needed by the server:

Post Man image

I am trying to create a function using http.get in order to retrieve these records in my application. I have created a service called listService that would take in the module name and prepare a header object. The service would then call an adapterService (containing my get function), that would prepare the headers and fire the request to the server. Unfortunately instead of getting a valid response I receive the following error:

"SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse () at XMLHttpRequest.onLoad (http://localhost:4200/vendor.js:13170:51) at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:2743:31) at Object.onInvokeTask (http://localhost:4200/vendor.js:42628:33) at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:2742:36) at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (http://localhost:4200/polyfills.js:2510:47) at ZoneTask.push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (http://localhost:4200/polyfills.js:2818:34) at invokeTask (http://localhost:4200/polyfills.js:3862:14) at XMLHttpRequest.globalZoneAwareCallback (http://localhost:4200/polyfills.js:3888:17)"

Upon adding the logs from the server I noticed the headers that were being sent in the request:

 Wed Mar 20 11:37:43 2019 [21570][-none-][FATAL] Array
(
    [Host] => localhost
    [Connection] => keep-alive
    [Accept] => application/json, text/plain, */*
    [Origin] => http://evil.com/
    [User-Agent] => Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36
    [Referer] => http://localhost:4200/profile
    [Accept-Encoding] => gzip, deflate, br
    [Accept-Language] => en-US,en;q=0.9
    [If-None-Match] => d41d8cd98f00b204e9800998ecf8427e
)

The data I'm sending is not even being added to the headers! I'm not sure why this is happening. I've checked the docs to see if I'm adding the http headers the wrong way, and have console logged at various points and everything seems to be fine up until the call to http.get. I really don't understand what's going on here.

Here is my code:

listService

import { Injectable } from '@angular/core';
import { JwtService } from 'src/app/services/jwt/jwt.service';
import { AdapterService } from 'src/app/services/adapter/adapter.service';
import { environment } from 'src/environments/environment';
import { NGXLogger } from 'ngx-logger';
import { Observable } from 'rxjs';
import { ToastrService } from 'ngx-toastr';
import { TranslatePipe } from 'src/app/pipes/translate/translate.pipe';

/**
* This property contains the attributes of the environment configuration.
*/
const API = environment.api;

@Injectable({
  providedIn: 'root'
})
export class ListService {

  /**
  * Constructor to initialize the jwt service, adapter service, logger and translation pipe
  */
  constructor(private adapter: AdapterService,
    private jwt: JwtService,
    private translate: TranslatePipe,
    private logger: NGXLogger,
    private toaster: ToastrService) { }

  /**
   * This method initialzes the parameters for the the Get call.
   *
   * @param  username
   * @param  password
   * @return
   */
  initializeParameters(module: string): any {
    let token = this.jwt.getToken();
    let params = {
      "module": module,
      "platform": API.platform,
      "oauth_token": token
    };
    return params;
  }

  /**
  * This method sends request for listing relevant data from module
  */
  listData(module: string) {
    let params = this.initializeParameters(module);
    this.adapter.get('customPortalApi/listRecords', params)
      .subscribe(
        response => {
          this.logger.warn(response);
        },
        error => {
          let errmsg = this.translate.transform("pages[login_page][responses][error][" + error.error + "]");
          this.toaster.error(errmsg); console.log(error);
        }
      )
  }
}

adapterService (header and get functions)

private requestHeaders(path: string, headerData: any) {
    let headers;
    if (path !== 'customPortalApi/customToken') {
        headers = new HttpHeaders();
        for(let key in headerData){
          let value = headerData[key];
          headers = headers.append(key, value);
        }
      }
        return headers;
    }

  /**
   * This method generates the GET api call.
   *
   * @param path
   * @param params
   * @method get
   * @return
   */
    get(path: string, data: any, params: HttpParams = new HttpParams()): Observable < any > {
    let headers = this.requestHeaders(path, data); 
    return this.http.get(`${API_URL}${path}`, headers)
            .pipe(catchError(this.formatErrors));
    }

dummy component (for call)

import { Component, OnInit } from '@angular/core';
import {ListService} from 'src/app/services/list/list.service';

/**
* This component is for testing
*/
@Component({
  selector: 'app-dummy',
  templateUrl: './dummy.component.html',
  styleUrls: ['./dummy.component.scss']
})
export class DummyComponent implements OnInit{
  constructor(private list: ListService){}

  ngOnInit(){
    this.list.listData("accounts");
  }
}

EDIT for anyone who wants to get an idea of how the header object looks like before making the call to http.get:

picture

Another Edit Could it be that CORS may be causing an issue? I have set Access-Control-Allow-Origin to "*". Here is my network activity once the I made changes proposed:

result

The REST service is being hit but it is not redirecting me to my API

The headers being logged on the server when I send via postman are:

Wed Mar 20 12:52:50 2019 [21570][1][FATAL] Array
(
    [Host] => localhost
    [Connection] => keep-alive
    [module] => Accounts
    [Cache-Control] => no-cache
    [oauth_token] => 9efe19d4d2ec3b557b4d0588a3f74d5d3cc0ed46
    [platform] => base
    [User-Agent] => Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36
    [Postman-Token] => 3ddc88e1-e7a8-700f-580b-801da5f0adde
    [Accept] => */*
    [Accept-Encoding] => gzip, deflate, br
    [Accept-Language] => en-US,en;q=0.9
    [Cookie] => download_token_base=e790d5a8-17a4-4110-98ab-a6648a0ef385
)

And these are working properly

Muhammad Hamza
  • 613
  • 13
  • 34
  • 1
    Try passing the headers as `this.http.get(`${API_URL}${path}`, {headers: headers})` – Ashish Ranjan Mar 20 '19 at 06:53
  • Hi @xyz, made the changes but now the call isn't even being made to the server and the console displays the following error: `Response for preflight has invalid HTTP status code 404.` – Muhammad Hamza Mar 20 '19 at 06:58

1 Answers1

1
get(path: string, data: any, params: HttpParams = new HttpParams()): Observable < any > {
let httpOptions ={headers: this.requestHeaders(path, data)}; 
return this.http.get(`${API_URL}${path}`, httpOptions)
        .pipe(catchError(this.formatErrors));
}

Try it like this. You need to pass an option object that contains the headers property.

https://angular.io/guide/http#adding-headers

Qellson
  • 532
  • 2
  • 7
  • Hi @Qellson, made the changes but now the call isn't even being made to the server and the console displays the following error: `Response for preflight has invalid HTTP status code 404`. Similar solution was given by @xyz just moments ago in the comments – Muhammad Hamza Mar 20 '19 at 07:07
  • Maybe this will help @noobdev : https://stackoverflow.com/questions/29954037/why-is-an-options-request-sent-and-can-i-disable-it – Qellson Mar 20 '19 at 12:35