0

I have a rest web service and now I want to make a post request from ionic 2 frontend app to authentication rest method.

On my login component I have:

...this._restClient.post(
                'authentication',
                body,
                (data) => this.handleSuccessAuthenticate(data),
                (data) => this.handleErrorAuthenticate(data)
            );...

On my provider my _restClient code is:

public post(resource: string, data: Object, onSuccess: restClient, onError: callbackRestClient) {
        var httpResult: Observable<Response>;


        if (data === null) {
            httpResult = this._http.post(this.getUrl(resource), '{}', { headers: this.getHeaders() });
        } else {
            httpResult = this._http.post(this.getUrl(resource), JSON.stringify(data), { headers: this.getHeaders() });
        }


        this.handleResult(httpResult, onSuccess, onError);
    }

I also have a private method to set headers:

   private getHeaders() {
        var headers = new Headers();
        headers.append('Accept', 'application/json');
        headers.append('Content-Type', 'application/json');
        headers.append('Access-Control-Allow-Origin', '*');
        headers.append('Access-Control-Allow-Credentials', 'true');
        headers.append("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE");
        headers.append("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token");

        return headers;
    }

I have the classic message:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

What I´m doing wrong?

Goldbones
  • 1,407
  • 3
  • 21
  • 55
  • 2
    See this a great Thierry's answer http://stackoverflow.com/questions/36768418/how-to-make-cors-enabled-http-requests-in-angular-2/36768488#36768488 – yurzui Jun 02 '16 at 18:39

1 Answers1

1

In fact, it's server-side issue and not an Angular2 one. The preflighted OPTIONS request need to return a Access-Control-Allow-Origin header in its response.

See these articles for more details:

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360