Getting "No 'Access-Control-Allow-Origin' header is present on the requested resource" error even though CORS is setup properly

Viewed 4578

Trying to access a web service in a different domain, with CORS enabled on the server. When I test out the web service with Postman, everything works fine and I do receive the following response headers:

Access-Control-Allow-Headers:Content-Type
Access-Control-Allow-Methods:GET, POST, DELETE, PUT, OPTIONS
Access-Control-Allow-Origin:*

When my web application (Angular 2) tries to POST to it, I get:

XMLHttpRequest cannot load http://example.com/mywebservice. No 'Access-Control-Allow-Origin' header is present on the requested resource.

I'm not sure why Postman seems to be receiving the proper variable setting but my browser is still preventing me from using it.

According to Chrome debugger, the preflight response seems to have worked fine:

Request Method:OPTIONS
Status Code:200 OK

When I try to access the GET portion of the web service, everything works fine:

getJob(id: number): Observable<Job> {

    let myParams = new URLSearchParams();
    myParams.append('id', id + "");

    let options = new RequestOptions({ headers: this.getHeaders(), params: myParams});

    return this.http
        .get(this.jobsUrl, options)
        .map(res => res.json().data as Job)
        .catch(this.handleError);
}

It's the POST portion of the web service that fails:

createJob(job: Job): Observable<any> {

    let options = new RequestOptions({ headers: this.getHeaders()});

    return this.http
        .post(this.jobsUrl, job, options)
        .map(res => res.json().jobID)
        .catch(this.handleError);
}

And here is getHeaders():

private getHeaders() {
    let headers = new Headers();
    headers.append('Content-Type','application/json');
    return headers; 
}
2 Answers
Related