Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No 'Access-Control-Allow-Origin' header is present on the requested resource - ionic 2 application

I receive the following error when i try to access my local server with a POST request:

XMLHttpRequest cannot load http://127.0.0.1:8000/api/v1/users/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.

My server allows CORS because I've tested it by sending the request with postman and it works.

Here is my code in the front-end:

private headers = new Headers({
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'GET, POST, OPTIONS, PUT, PATCH, DELETE',
    'Access-Control-Allow-Headers': 'X-Requested-With,content-type',
    'Access-Control-Allow-Credentials': true 
});


postLogin(data) {
    console.log(data);
    return new Promise((resolve) => {
        this.http.post(this.api + "users/login", data, {headers: this.headers})
            .map(res => res.json())
            .subscribe(answer => {
                 this.loggedIn = true;
                 this.token = answer.token;
                 resolve(answer);
            });
    });
 }

PS: I did not get this error with a GET request.

I tried to put a proxy and it doesn't change anything :(

This is my ionic.config.json:

{
  "name": "hardShop",
  "app_id": "",
  "v2": true,
  "typescript": true,
  "proxies": [
      {
          "path": "/api",
          "proxyUrl": "http://127.0.0.1:8000"
      }
  ]
}
like image 427
bondif Avatar asked Jun 10 '17 10:06

bondif


1 Answers

Try again using this plugin in your browser.

It allows you to ajax request any address from any source, bypassing http/https security requirements or other limitations set by browsers (known as CORS). Practically it injects the 'Access-Control-Allow-Origin': '*' header in the received response before it is passed on to your app.

Please keep in mind that this is a band-aid solution, predominantly for development. Your server's response has to actually have the 'Access-Control-Allow-Origin': '*' header, preferably with a more specific value than *.

What you are doing now has practically no effect, since you as the client are sending a request with that header to the server, who then promptly ignores it. What matters is that the server has this header in his response to your client.

Postman doesn't apply CORS as far as i know, so maybe that's why it's not affected.

like image 71
maninak Avatar answered Sep 20 '22 21:09

maninak