2

Trying to understand why such a simple rest call api not working from localhost (using angular-cli).

This is the service code:

commandsUrl ='http://www.mocky.io/v2/...';
  headers = new Headers({ 'Access-Control-Allow-Origin': '*' });
  options = new RequestOptions({ headers: this.headers, withCredentials: true });

  getMyList (): Observable<any> {
    return this.http.get(this.commandsUrl, this.options)
      .map(this.extractData)
      .catch(this.handleError);

  }
  private extractData(res: Response) {
    let body = res.json();
    return body.data || { };
  }
  private handleError (error: Response | any) {
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }

The error from browser is:

XMLHttpRequest cannot load http://www.mocky.io/v2/... Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

1 Answer 1

0

You have to read up on CORS. Before your real AJAX request is sent, the GET, an OPTIONS request is sent and the server must respond with `Access-Control-Allow-Origin' headers that give you permission to access it.

That is, the server at 'http://www.mocky.io/v2/...' has to be configured to accept CORS requests from your server (or using a wildcard)

https://www.html5rocks.com/en/tutorials/cors/

Sign up to request clarification or add additional context in comments.

7 Comments

I have added header Access-Control-Allow-Origin to the response, but doesn't seems to change at all.
You added the header to the response of mocky.io/v2? Do you have a URL I can call or a screenshot proving that the server is returning it? Your code is adding the header on request from the client, which doesn't do anything, the header must be sent as a response header.
Weird, it seems to work here. jsbin.com/qugaduqubo/1/edit?html,js,output but I don't see an OPTIONS request being made, which is the request that is probably not implemented
I am thinking maybe the problem is in angular-cli, something need to be configared maybe
I run an angular2 app that does CORS and I never had to configure anything. It's pretty weird. As a debugging option, I would try to run the XHR directly (without using angular as in the jsbin I linked to)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.