Karl Bateman Karl Bateman - 4 years ago 409
HTTP Question

Angular 2 CORS issues

I have the following Angular 2 http request;

const endpoint = '<auth_url>';
const body = {
prompt: 'consent',
grant_type: 'authorization_code',
redirect_uri: '<redirect_url>',
code: '<authorization_code>'

const headers = new Headers();
headers.append('Authorization', 'Basic <auth>');
headers.append('Content-Type', 'application/x-www-form-urlencoded')

const options = new RequestOptions({ headers });

this.http.post(endpoint, body, { headers: headers })
.map(res => res.json())
data => console.log(JSON.stringify(data)),
error => console.error(JSON.stringify(error)),
() => console.log('Request complete')

This is connecting to a
which has been attached to an ExpressJS instance, the issue I am having is with CORS as the request ends up as OPTIONS on the server because of preflight. This shouldn't be the case as I have specified the
header as seen above. Annoyingly I am trying to figure out whether this is an issue with the server or my Angular2 code?

Would I need to explicitly enable CORS on an ExpressJS application and if not, why would setting the correct header on the POST have no effect?

Answer Source

Yes, you need to enable CORS on the server side. That is if you have control on the server. Here are the Headers that should be returned from the server to enable CORS

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET,POST,PUT,DELETE
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept

You can share some details about your server like if you want to add these headers from the code or in the WebServer itself.

Regarding the question about the reason why setting the headers in the POST request has no effect. The browser issues an OPTION request before your XHTTP request to ask the permission from the server about accepting CORS.

So, if you have control on the server, then you can add the headers I mentioned before. If not, then you can use some browser plugins to overcome this check.

Here is how the network tab in the developer tools should look like

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download