How can I support cors when using restify


Question

I have a REST api created with the restify module and I want to allow cross-origin resource sharing. What is the best way to do it?

1
44
2/2/2019 9:54:21 AM

Accepted Answer

You have to set the server up to set cross origin headers. Not sure if there is a built in use function or not, so I wrote my own.

server.use(
  function crossOrigin(req,res,next){
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    return next();
  }
);

I found this from this tutorial. http://backbonetutorials.com/nodejs-restify-mongodb-mongoose/

60
1/24/2013 5:09:40 PM

The latest version of Restify provides a plugin to handle CORS.

So you can now use it like this:

server.use(restify.CORS({

  // Defaults to ['*'].
  origins: ['https://foo.com', 'http://bar.com', 'http://baz.com:8081'], 

  // Defaults to false.
  credentials: true,

  // Sets expose-headers.
  headers: ['x-foo']   

}));

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon