benzata
benzata

Reputation: 41

Angular / API consuming - request header - CORS proxy

I am stuck.. Please help.

I am trying to fetch data from an API (the API is already set-up).

I can successfully fetch the data when using Postman. I just add as header the x-api-key.

Postman

I would need to send GET requests and each request must contain a private API-Key in the http request-header like in the following example: x-api-key: TcKkYuizu67bsamplexeF4AGTnGWgY7E8MCiTEST

But I can't seem to successfully add the x-api-key in the header, using Angular. I thought that it was because of CORS preflight, but I am almost certain this is not the reason.

I have added CORS changer and Postman Interceptor extensions.

Using the Postman Interceptor extension, I noticed that something is not right. The x-api-key is not classified as a header at all and the key itself can't be found:

Postman Interceptor

Here are the errors from Chrome console:

Chrome Console

And here is my app.component.ts code:

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'x-api-key': 'PE84t4CCUC5e7JaGqSeyH7WdRfU6rhoRa6*****',
    'Authorization': 'x-api-key PE84t4CCUC5e7JaGqSeyH7WdRfU6rhoRa6*****'
  })
};

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'API';

  constructor(private http: HttpClient) {
    console.log('test');
  }
  ngOnInit(){
    let obs = this.http.get('https://api-proxy.***/GetChannels', httpOptions);
    obs.subscribe((response) => console.log(response));
  }
}

Angular CLI: 7.1.1 Node: 11.3.0

Upvotes: 0

Views: 1148

Answers (2)

georgeawg
georgeawg

Reputation: 48968

x-api-key is not a CORS safelisted request header. It will trigger an OPTIONS request which must have a successful response or the XHR will be blocked by browser.

There's no way for chrome plugin to modify the response HTTP status code based on current chrome extension API. The solution is to use a CORS proxy that responds properly to the OPTIONS request. For more information, see Disable same origin policy in Chrome.

Upvotes: 1

Viseshini Reddy
Viseshini Reddy

Reputation: 819

Content-Type header specifies the media type of the request objects you're sending to the server. Because you're just getting JSON data from the server you should set the Accept header to the kind of response you want i.e., Accept: application/json.

Upvotes: 1

Related Questions