How can I support cors when using restify

36,620

Solution 1

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/

Solution 2

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']   

}));

Solution 3

This works for me:

var restify = require('restify');

var server = restify.createServer();

server.use(restify.CORS());

server.opts(/.*/, function (req,res,next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", req.header("Access-Control-Request-Method"));
    res.header("Access-Control-Allow-Headers", req.header("Access-Control-Request-Headers"));
    res.send(200);
    return next();
});

server.get('/test', function (req,res,next) {

    res.send({
        status: "ok"
    });
    return next();
});

server.listen(3000, function () {
    console.log('%s listening at %s', server.name, server.url);
});

Solution 4

This is what worked for me:

function unknownMethodHandler(req, res) {
  if (req.method.toLowerCase() === 'options') {
      console.log('received an options method request');
    var allowHeaders = ['Accept', 'Accept-Version', 'Content-Type', 'Api-Version', 'Origin', 'X-Requested-With']; // added Origin & X-Requested-With

    if (res.methods.indexOf('OPTIONS') === -1) res.methods.push('OPTIONS');

    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Headers', allowHeaders.join(', '));
    res.header('Access-Control-Allow-Methods', res.methods.join(', '));
    res.header('Access-Control-Allow-Origin', req.headers.origin);

    return res.send(204);
  }
  else
    return res.send(new restify.MethodNotAllowedError());
}

server.on('MethodNotAllowed', unknownMethodHandler);

I this code was taken from https://github.com/mcavage/node-restify/issues/284

Solution 5

CORS Plugin is deprecated in favor of https://github.com/Tabcorp/restify-cors-middleware. (Source: https://github.com/restify/node-restify/issues/1091.)

Below is a sample code regarding how to use

const corsMiddleware = require('restify-cors-middleware')

const cors = corsMiddleware({
  preflightMaxAge: 5, //Optional
  origins: ['http://api.myapp.com', 'http://web.myapp.com'],
  allowHeaders: ['API-Token'],
  exposeHeaders: ['API-Token-Expiry']
})

server.pre(cors.preflight)
server.use(cors.actual)
Share:
36,620

Related videos on Youtube

Santhosh
Author by

Santhosh

Smalltalk programmer

Updated on May 11, 2020

Comments

  • Santhosh
    Santhosh about 4 years

    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?

  • Cheeso
    Cheeso almost 11 years
    which version of restify? (you said "last version of restify...")
  • Cheeso
    Cheeso almost 11 years
    This worked for me, but I also needed to add server.use(restify.fullResponse()); prior to the call to server.on(...).
  • Daniele Vrut
    Daniele Vrut over 10 years
    @Jean-MichelTrayaud: this doesn't work for me... I'm getting Origin 192.168.2.124 is not allowed by Access-Control-Allow-Origin. Any help will be apreciated :)
  • Jean-Michel Trayaud
    Jean-Michel Trayaud over 10 years
    think we need more information... GET or POST in first time (POST is really a nightmare with CORS)
  • J.P.
    J.P. about 10 years
    This almost worked for me. I had to use server.opts({path: '/customers', version: '0.0.1'}, unknownMethodHandler);. With on, the method just wasn't called.
  • Jeff Fairley
    Jeff Fairley over 9 years
    I'm using Restify v2.8.3, and some of these headers are already enabled by default. Check out the defaults in ./node_modules/restify/lib/plugins/cors.js.
  • Mark Berryman
    Mark Berryman over 8 years
    Testing against Restify 3.0.3, using restify.CORS() by itself was sufficient. No need for restify.fullResponse(), but in the request, you need to specify the Origin header. See related code comment in cors.js.
  • coderofsalvation
    coderofsalvation over 8 years
    typo alert: the last else needs an extra bracket
  • guagay_wk
    guagay_wk over 8 years
    For some reason, the other answers did not work for me. Yours did. I wonder if it has something to do with changes made to latest versions of restify.
  • eenblam
    eenblam almost 8 years
    Since this answer has been around for a while and people are asking about versions in the comments below other questions, I'd like to report that this answer is still valid for me with Restify 4.1.0.
  • Maciej Krawczyk
    Maciej Krawczyk almost 7 years
    This plugin has a strange behavior. If the origin matches one of the array, it will return the matching origin in the response header, which is expected. If it doesn't match however, it will return a wildcard. It will still fail if you make a credentialized cors request, because then the origin must not be *. But why return * anyway?
  • Ahmer Saeed
    Ahmer Saeed almost 7 years
    i am using restify 5.0.1, and can't find the solution regarding CORS
  • Ahmer Saeed
    Ahmer Saeed almost 7 years
    i am using restify 5.0.1, and can't find the solution regarding CORS
  • Mitro
    Mitro over 6 years
    I use it with 6.0.1
  • terrymorse
    terrymorse almost 6 years
    This avoids the 404 "Method not allowed" response from restify for OPTIONS preflight requests. The CORS cross-origin problem must be handled separately--see "crossOrigin function above for a fix that problem.
  • Christallkeks
    Christallkeks over 4 years
    Note that this plugin has been removed in favour of a middleware solution (source)
  • Sam
    Sam almost 3 years
    This is the only solution which works right now in 07/2021, everything else is obsolete or has a bug, also the "new" middleware. restify is a mess, I recommending anyone new to NOT use it.
  • Sam
    Sam almost 3 years
    doesnt work, it's bugged, broken or whatever
  • Prachi
    Prachi over 2 years
    So it's not just me who's had trouble with the plugins! Phew.
  • Prachi
    Prachi over 2 years
    Btw, when I use this, I get 404s on my endpoints. :(