Atinux
Atinux

Reputation: 1703

CORS with Express.js and jQuery.ajax

I use express.js for my server, with this headers:

x-powered-by: Express
connection: keep-alive
content-length: 2
content-type: application/json; charset=utf-8
access-control-allow-methods: GET,PUT,POST,DELETE
access-control-allow-origin: *
access-control-allow-headers: x-requested-with

I call res.header to allow CORS:

res.header("Access-Control-Allow-Origin:", "*");
res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");  
res.header("Access-Control-Allow-Headers", "x-requested-with");

You can test here : http://my-api.rs.af.cm/api/products

For my front-end, I use jsbin and I call my server with $.ajax: http://jsbin.com/apizez/37/edit

Result here: http://jsbin.com/apizez/37

You can look at the JS console, you will see this error:

XMLHttpRequest cannot load http://my-api.rs.af.cm/api/products. Origin http://jsbin.com is not allowed by Access-Control-Allow-Origin.

I read all others answers on CORS and I don't want to use easyXDM.

Upvotes: 4

Views: 7175

Answers (2)

Felippe Regazio
Felippe Regazio

Reputation: 389

You must take in consideration your preflight request also. I suggest you to add the "cors" npm package on your project, and start it with this following configurations:

const cors = require('cors');

app.use(cors({
    credentials: true,
    preflightContinue: true,
    methods: ['GET', 'POST', 'PUT', 'PATCH , 'DELETE', 'OPTIONS'],
    origin: true
});

This will enable Cross Origin Requests for any address with the listed methods. The origin parameter is very flexible, you can delimiter a set of address, all address or by regex, for example. Here is the package docs:

https://expressjs.com/en/resources/middleware/cors.html

Upvotes: 0

Atinux
Atinux

Reputation: 1703

Thanks to Ryan Olds to help me to understand how CORS requests work.

Here the correct headers:

res.header('Access-Control-Allow-Origin', req.headers.origin || "*");
res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,HEAD,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'content-Type,x-requested-with');

All my requests had that headers in their response.

I use $.getJSON for GET requests with jQuery, otherwise It doesn't work.

You can see the example here: http://jsbin.com/uwevuc/2/edit

http://jsbin.com/uwevuc/2

Upvotes: 5

Related Questions