Matt McCarthy
Matt McCarthy

Reputation: 484

HttpClient ignores headers passed to .get()

Not a duplicate: Angular HTTPClient ignores headers. This issue was solved by including a body parameter, which does not exist with .get(). The options parameter is correctly set, from what I can tell.

As the title says, I'm trying to use HttpClient.get(), but I get errors. Here's the method call:

private search(): Observable<Blob.IClientData[]> {
  const url =
    environment.origin + environment.baseUrl + '/search/' + this.query;
  const retrieved = new Date();
  const headers = new HttpHeaders({
    'Access-Control-Allow-Origin': environment.origin,
    'Content-Type': 'application/json; charset=UTF-8',
    Allow: 'GET',
    Accept: '*/*',
  });

  return this._http.get<Blob.IClientData[]>(url, { headers: headers }).pipe(
    map((response: Blob.IResponseBody[]) => {
      console.log(response);
      const results: Blob.IClientData[] = response.map(
        (body: Blob.IResponseBody) => {
          const clientData: Blob.IClientData = {
            id: body['id'],
            word: body['word'],
            descriptor: body['descriptor'],
            partSpeech: body['partSpeech'],
            tense: body['tense'],
            icon: body['icon'],
            md5: body['md5'],
            retrieved: retrieved,
          };

          return clientData;
        }
      );

      return results;
    })
  );
}

And the console errors:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/api/v0-alpha/search/query. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/api/v0-alpha/search/query. (Reason: CORS request did not succeed).
ERROR 
Object { headers: {…}, status: 0, statusText: "Unknown Error", url: "http://localhost:8000/api/v0-alpha/search/query", ok: false, name: "HttpErrorResponse", message: "Http failure response for http://localhost:8000/api/v0-alpha/search/query: 0 Unknown Error", error: error }
core.js:6456

It says But I did define it!

According to Jota.Toledo's answer on Adding a HTTP header to the Angular HttpClient doesn't send the header, why?, one option of defining headers to be passed to HttpClient is as follows (this is the construct I use):

const headers = new HttpHeaders({'h1':'v1','h2':'v2'});

I know that url is being constructed properly, as the error messages point to the right address (http://localhost:8000/api/v0-alpha/search/query). Execution never reaches the console.log() statement because there is no response, so changing things inside pipe() won't help at this stage.

What else can I try?

Update

environment.ts

export const environment = {
  production: false,
  origin: 'http://localhost:8000',
  baseUrl: '/api/v0-alpha',
};

Upvotes: 0

Views: 481

Answers (1)

Efran Cobisi
Efran Cobisi

Reputation: 6474

Access-Control-Allow-Origin is a response header, not a request header (see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin): you should configure CORS appropriately on your back-end, so that it permits cross-origin requests (the browser will made a pre-flight request just to check that).

Also, apparently, you are accessing your app from an origin which is not the one of your API (http://localhost:8000): if you are still prototyping and do not want to deal with CORS on your back-end, you may just want to run everything from the same origin (protocol + host + port).

Upvotes: 1

Related Questions