Skip to content

CORS

Created: 2016-01-05 19:35:21 -0800 Modified: 2020-10-21 08:57:34 -0700

Read this: https://simonplend.com/how-to-fix-those-confusing-cors-errors-when-calling-your-express-api/

When in a browser, a preflight request is sent before actually performing the intended operation. For example, if you try doing a GET on foo.com/users, it will first send an OPTIONS request to figure out which HTTP methods are allowed (so “GET” in this case) and what headers can be set (e.g. in Bot Land’s case: “bltoken”). This means that if you don’t have an OPTIONS handler set up on your REST server, browsers won’t get any response when they send their preflight request.

This function will reply with the accepted headers on the OPTIONS route.

I set this up with Restify by doing this:

this.server.opts(route, function(req, res, next) {

res.setHeader(‘Access-Control-Allow-Headers’, [‘bltoken’, ‘Content-Type’]);

res.setHeader(‘Access-Control-Allow-Methods’, [‘GET’, ‘PATCH’]);

res.send(200);

next();

});

For more information, see: http://stackoverflow.com/a/10636765

cURL can always make a request to the server; it is unaffected by CORS.

This tripped me up when I was trying to figure out why a CORS error was reporting when I could properly request the URL through cURL. It turned out to be a legitimate server problem.