简体   繁体   中英

How to bypass the cross origin error using angular 6 (Firefox CORS Error, Chrome Preflight Error)

I am developing a front end to be used as a client for a rest-api. Angular 6 is used.

The problem is that when I send a post request using HttpClient, I get this cross origin error. my code:

Service:

export class ApiConfigLogin {
      constructor(private http: HttpClient,
        private dataSrvc: DataService) {}

      private _url = this.dataSrvc.getMainUrl() + '/sec-login';

      private options = {
        headers: new HttpHeaders().set('Content-Type', 'application/json')
      };
      getResults(reqbody): Observable < ApiConfigLoginInterface > {
        console.log(this._url);
        return this.http.post < ApiConfigLoginInterface > (this._url, reqbody, this.options);
      }
    }

Component.ts

this._ApiConfigLogin.getResults(body)
      .subscribe(data => {
        this.enableForms();
        if (data.status === 401) {
          this.lowerMessage = data.message;
        } else {
          console.log(1);
        }
      });

in mozilla firefox:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://8888.8888.8888.8888:8888/address/sec-login . (Reason: CORS request did not succeed).

in google chrome:

Failed to load http://8888.8888.8888.8888:8888/address/sec-login : Response for preflight is invalid (redirect)

I have tested Allow control extensions to my browsers. It is good to know that I have a content-type header:

CORS errors occur when you call a service using a URL that is not the same as the URL used to load the Web app, up to and including the port. This is a security feature built into your browsers.

To avoid it, your server needs to allow cross-origin requests by adding headers. You can manually add the headers, which takes a bit of effort, or, if you are using something like Spring, there will be an annotation.

there are ways around the it; See this on GitHub about how to handle CORSS client-side:

JSONP

WARNING: This isn't allowed on every API and may break when calling certain APIS

You can bypass CORS in production using JSONP which stands for JSON with Padding and is kinda also a 'hack'. But it is a widely used hack which many APIs support. You are not sending a pure JSON-request but you are wrapping your data in a function that gets evaluated. JSONP explained in the link below:

or use a proxy:

Proxy

WARNING: Great services, but you are dependent on these services to work, if they break or go down, so does your app

You can use a service that proxies your request and automatically enable CORS for your:

Then you have to call your API by prepending one of these URLs to your request, for example:

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