How to use the restify.CORS function in restify

To help you get started, we’ve selected a few restify examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github bhoriuchi / bookshelf-pagemaker / example / pagemaker-demo.js View on Github external
return JSON.stringify(body);
			}
		},
		acceptable: ['application/json', 'text/html']
};





// set up the restify server with CORS enabled and body/query parsers
var server = restify.createServer(r_config);
server.pre(restify.pre.sanitizePath());
server.use(restify.bodyParser({ mapParams: false }));
server.use(restify.queryParser());
server.use(restify.CORS());
server.use(restify.acceptParser(server.acceptable));


// set up routes
server.get('/pagemaker/datatables', makeDatatables);
server.get('/pagemaker/datatables/example', makeDatatablesHtml);
server.get('/pagemaker/pagemaker', makePagemaker);
server.get('/pagemaker/custom', makeCustom);
server.get('/pagemaker/test/:type', makeTest);

// start the server
server.listen(8080, function() {
	console.log('Test Server %s listening at %s', server.name, server.url);
});
github fidelthomet / WHERE / where.js View on Github external
function initServer() {

	var server = restify.createServer({
		name: 'WHERE',
		version: pjson.version
	})

	// server.pre(restify.pre.sanitizePath());

	// Unsure if this is needed at some point
	// server.use(restify.acceptParser(server.acceptable))
	// server.use(restify.queryParser())
	// server.use(restify.bodyParser())

	server.use(restify.CORS());

	// define routes
	server.get('/q/:geojson', function(req, res) {
		res.send(respond(req.params.geojson))
	})

	server.get('/q/:geojson/:geometry', function(req, res) {
		res.send(respond(req.params.geojson, req.params.geometry))
	})

	server.get('/q/:geojson/:geometry/:props/', function(req, res) {
		res.send(respond(req.params.geojson, req.params.geometry, req.params.props))
	})

	server.get('/q/:geojson/:geometry/:props/:options', function(req, res) {
		res.send(respond(req.params.geojson, req.params.geometry, req.params.props, parseOptions(req.params.options)))
github jeresig / idyll / server / app.js View on Github external
fs.readdirSync(modelsDir).forEach(function (file) {
    if (~file.indexOf(".js")) {
        require(modelsDir + "/" + file);
    }
});

var routes = require("./routes");
var users = require("./app/controllers/users");
var jobs = require("./app/controllers/jobs");

var server = restify.createServer({
    name: "Idyll"
});

server.use(restify.CORS());
server.use(restify.bodyParser());
server.use(restify.queryParser());
server.use(restify.gzipResponse());

server.use(function(req, res, next) {
    if (req.params && req.params.jobId) {
        return jobs.job(req, res, next, req.params.jobId);
    }
    next();
});

// Dynamic API used by clients
server.get("/jobs", routes.getJobs);
server.get("/jobs/:jobId", users.auth(), routes.taskQueue);
server.post("/jobs/:jobId", users.auth(), routes.saveResults);
server.get("/jobs/:jobId/tasks/:task", users.auth(), routes.getTask);
github Fluidbyte / Nodedit-Server / server.js View on Github external
});
    
} else {
    
    // Config non-SSL Server
    server = restify.createServer({
        name: "fsapi"
    });
    
}

// Additional server config
server.use(restify.acceptParser(server.acceptable));
server.use(restify.queryParser());
server.use(restify.bodyParser());
server.use(restify.CORS());

// Regular Expressions
var commandRegEx = /^\/([a-zA-Z0-9_\.~-]+)\/([a-zA-Z0-9_\.~-]+)\/(.*)/,  // /{key}/{command}/{path}
    pathRegEx = /^\/([a-zA-Z0-9_\.~-]+)\/(.*)/;  // /{key}/{path}


/**
 * UnknownMethod handler
 */
function unknownMethodHandler(req, res) {
  if (req.method.toLowerCase() === 'options') {
    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-Methods', 'GET, POST, PUT, DELETE');
github xpush / node-xpush / lib / xpush.js View on Github external
var serverOption = options.server || {};

  if (!serverOption.name) serverOption.name = 'xpush';

  if (options.httpsServerOptions) {
    serverOption.httpsServerOptions = options.httpsServerOptions;
    options.protocol = 'https';
  } else {
    options.protocol = 'http';
  }

  var server = restify.createServer(serverOption);

  var io = socketio.listen(server.server);

  server.use(restify.CORS());
  server.on('error', onError);

  var channelServer = require('./xpush-channel-server.js');
  channelServer.init(server, io, options, function(err, result) {

    if (err) {
      console.error(err, result);
      if (cb) cb(err, result);
    } else {
      server.listen(port, function() {

        console.log(welcome(options), '"CHANNEL server" listening at ' + host + ":" + port);

        channelServer.emit("started", host, port);
        channelServer._addNamespace();
github xbrowsersync / api / api.js View on Github external
server = restify.createServer({
            log: log,
            name: global.apiName
        });

        server.listen(config.server.port, config.server.host, function () {
            console.log('%s: %s started on %s:%d ...', Date(Date.now()), global.apiName, config.server.host, config.server.port);
        });
        
        server.pre(function (req, res, next) {
            req.log.info({ req: req });
            return next();
        });

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

        server.use(restify.queryParser());
        
        server.use(restify.bodyParser({
            maxBodySize: config.maxSyncSize
        }));

        server.use(restify.throttle({
            rate: config.throttle.rate,
github mattolde / study-workout-server / app.js View on Github external
var restify = require('restify');
var mongojs = require("mongojs");

var appName = 'study-workout';

var ip = '127.0.0.1';
var port = '8080';
 
var server = restify.createServer({
  name : appName
});
 
server.use(restify.queryParser());
server.use(restify.bodyParser());
server.use(restify.CORS());

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

var connection_string = '127.0.0.1:27017/' + appName;
var db = mongojs(connection_string, [appName]);
var workouts = db.collection("workouts");
var exercises = db.collection("exercises");

var findAllWorkouts = function(req, res , next){
  res.setHeader('Access-Control-Allow-Origin','*');

  workouts.find(function(err , success){
    
    if(success){
github plotly / falcon / backend / setupServers.js View on Github external
};

    sequelizeManager.log('Closing HTTP server.', 1);
    if (httpServer) {
        httpServer.close();
    }
    httpServer = null;

    httpsServer = restify.createServer(httpsOptions);
    /*
     * parsed content will always be available in req.query,
     * additionally params are merged into req.params
     */
    httpsServer.use(restify.queryParser());
    httpsServer.use(restify.bodyParser({ mapParams: true }));
    httpsServer.use(restify.CORS({
        origins: acceptRequestsFrom.domains,
        credentials: false,
        headers: ['Access-Control-Allow-Origin']
    })).listen(process.env.PORT || OPTIONS.port);

    /*
     * https://github.com/restify/node-restify/issues/664
     * Handle all OPTIONS requests to a deadend (Allows CORS to work them out)
     */
    httpsServer.opts( /.*/, (req, res) => res.send(204));

    setupRoutes(httpsServer, serverMessageReceive(responseTools));

};
github plotly / falcon / backend / routes.js View on Github external
'x-requested-with',
            'x-forwarded-for',
            'x-real-ip',
            'x-customheader',
            'user-agent',
            'keep-alive',
            'host',
            'accept',
            'connection',
            'upgrade',
            'content-type',
            'dnt',
            'if-modified-since',
            'cache-control'
        ];
        server.use(restify.CORS({
            origins: getSetting('CORS_ALLOWED_ORIGINS'),
            credentials: true,
            headers: headers
        }));
        headers.forEach(header => restify.CORS.ALLOW_HEADERS.push(header));
        Logger.log('CORS_ALLOWED_ORIGINS: ' + JSON.stringify(
            getSetting('CORS_ALLOWED_ORIGINS')
        ), 2);
        server.opts(/.*/, function (req, res) {
            res.header(
                'Access-Control-Allow-Headers',
                restify.CORS.ALLOW_HEADERS.join(', ')
            );
            res.header(
                'Access-Control-Allow-Methods',
                'PATCH, POST, GET, DELETE, OPTIONS'
github dominiklessel / node-restify-boilerplate / app.js View on Github external
plugins.push(restify.bodyParser());
plugins.push(restify.gzipResponse());

server.use(plugins);

/**
 * CORS
 */

var corsOptions = {
  origins: nconf.get('CORS:Origins'),
  credentials: nconf.get('CORS:Credentials'),
  headers: nconf.get('CORS:Headers')
};

server.pre(restify.CORS(corsOptions));

if (corsOptions.headers.length) {
  server.on('MethodNotAllowed', require(path.join(__dirname, 'helpers', 'corsHelper.js'))());
}

/**
 * Request / Response Logging
 */

server.on('after', restify.auditLogger({
  log: Logger
}));

/**
 * Middleware
 */