简体   繁体   中英

No 'Access-Control-Allow-Origin' header is present on the requested resource - Angular 5

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...

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM