No 'Access-Control-Allow-Origin' header is

2019-08-26 06:21发布

I'm trying to access web service from my angular service with cross-origin related headers set. But still, I'm not able to access the web service. The browser keeps saying,

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. The response had HTTP status code 403.

I'm able to access the same URL in the browser (chrome) and postman but not in angular application.

private headers = new HttpHeaders()
.set('Access-Control-Allow-Origin', '*')
.set('Content-Type', 'application/json;charset=UTF-8')
.set('Access-Control-Allow-Headers', '*')
.set('Access-Control-Allow-Methods', 'GET, OPTIONS');

public getData(): Promise<Object> {
  return this._http.get(this._url, {headers: this.headers})
  .toPromise()
  .then(response => {
      return response;
    }
  )
  .catch(testService.handleError);

}

Is there anything I'm missing here...

3条回答
forever°为你锁心
2楼-- · 2019-08-26 07:01

Try JSONP. Basically as per WC3Schools states

JSONP is a method for sending JSON data without worrying about cross-domain issues.

JSONP does not use the XMLHttpRequest object.

Here's an explanation of how JSONP works

查看更多
相关推荐>>
3楼-- · 2019-08-26 07:02

There are multiple ways to solve this issue, but first you will need to identify the extra request header parameter that is getting send by the client, if any.

It's earlier to spot this by using any of the broswer's developer console. Another pointer is to check the response/error for options call if any.

Once identified, you will need to enable the appropriate response parameters from the server, in your case it seems the options call is not setting Access-Control-Allow-Origin in the response.

Let me know if this helped you diagnose your issue.

查看更多
聊天终结者
4楼-- · 2019-08-26 07:22

So, there is two approaches

  1. If you have an access to edit the web service.

    You need to allow Cross Origin Resource sharing. if u are using Node.js here is an example of code to add

    // ~ Cross origin resource sharing ~ //
    var cors = require('cors');
    // ~ Initialize the app ~ //
    var app = express();
    // ~ Enbling CORS ~ //
    app.use(cors());
    
  2. You can add a browser extension that enables you fix CORS errors for the angular app while running on browser.

Here is for chrome https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en

Here is for Mozilla https://addons.mozilla.org/en-US/firefox/addon/cors-everywhere/

You can read more at https://enable-cors.org/


I hope that helps. If there is any error let me know through comments.

查看更多
登录 后发表回答