Problem sending apikey in angular header http 4

0

I have an Api REST that requires the apikey in the headers to validate, I am doing the query with angle 4, but the apikey is not sent in the headers.

If I do the query with PostMan it works without problem. I'm stuck at this point, I appreciate your help friends.

I need to send the "apikey" in the headers of the request something like that.

This is the component code.

import { Component } from '@angular/core'
import { OnInit } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http'
import 'rxjs/add/operator/map'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  private apiURL = 'http://192.168.1.53/joinn-api/v1'
  data: any = {}

  constructor(private http: HttpClient){
    this.getData()
    this.getEvents()

  }

  getData(){
    let headers = new HttpHeaders()
    headers = headers.append('Content-Type', 'application/json; charset=utf-8')
    return this.http.get(this.apiURL + '/event/?token=cf6fb41f1d21834d34c8a8c8b3827181', {headers: headers})
      .map((res: Response) => res.json())
  }

  getEvents(){
    this.getData().subscribe(data => {
      console.log(data)
    })

  }



}
    
asked by Alejandro Restrepo 22.11.2017 в 01:18
source

2 answers

0

If the Backend what you expect to receive is the apikey in the headers, and not as a parameter in the URL (query) you have the following:

getData(){
  let headers = new HttpHeaders();
  headers = headers.set('apikey', 'cf6fb41f1d21834d34c8a8c8b3827181');
  return this.http.get(this.apiURL + '/event', { headers: headers.set('Content-Type', 'application/json'))
  .map(response => response.json());
}


getEvents(){
  this.getData().subscribe(
    event => console.log(event),
    error => console.error('Error: ' + error),
    () => console.log('Completedo!')
  );
}

I hope and serve you and solve your problem. Greetings.

    
answered by 22.11.2017 в 07:33
0

Send your header apiKey by setting it with the HttpInterceptor from Angular +4, as well you will not have to repeat it in every request you make against your API.

Source

    
answered by 27.12.2017 в 00:39