簡體   English   中英

使用restify時如何支持cors

[英]How can I support cors when using restify

我有一個使用 restify 模塊創建的 REST api,我想允許跨源資源共享。 最好的方法是什么?

您必須設置服務器以設置跨源頭。 不確定是否有內置的 use 函數,所以我自己寫了一個。

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

我從本教程中找到了這個。 http://backbonetutorials.com/nodejs-restify-mongodb-mongoose/

最新版本的 Restify 提供了一個插件來處理 CORS

所以你現在可以像這樣使用它:

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

}));

這對我有用:

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);
});

這對我有用:

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);

我這個代碼取自https://github.com/mcavage/node-restify/issues/284

CORS 插件已棄用,取而代之的是https://github.com/Tabcorp/restify-cors-middleware (來源: https : //github.com/restify/node-restify/issues/1091 。)

以下是有關如何使用的示例代碼

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)

如果有人在 2018 年 2 月遇到這個問題,似乎已經引入了一個錯誤,我無法讓restify-cors-middleware工作。

我現在正在使用這項工作:

server.pre((req, res, next) => {
   res.header("Access-Control-Allow-Origin", "*");
   next();
});

為了啟用 CORS 進行基本身份驗證,我執行了以下操作。 它沒有工作,直到.pre方法,替代了的.use方法

server.pre(restify.CORS({
  origins: ['https://www.allowedip.com'],  // defaults to ['*']
  credentials: true,
  headers: ['X-Requested-With', 'Authorization']
}));
server.pre(restify.fullResponse());

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

      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(200);
   } else {
      return res.send(new restify.MethodNotAllowedError());
   }
}

server.on('MethodNotAllowed', unknownMethodHandler);

我在我的 restify 基礎應用程序上這樣做:

//setup cors
restify.CORS.ALLOW_HEADERS.push('accept');
restify.CORS.ALLOW_HEADERS.push('sid');
restify.CORS.ALLOW_HEADERS.push('lang');
restify.CORS.ALLOW_HEADERS.push('origin');
restify.CORS.ALLOW_HEADERS.push('withcredentials');
restify.CORS.ALLOW_HEADERS.push('x-requested-with');
server.use(restify.CORS());

您需要先使用restify.CORS.ALLOW_HEADERS.push 方法將您想要的header 推送到restify 中,然后使用CORS 中間件啟動CORS 功能。

以前的大部分答案來自 2013 年,並使用已棄用的示例! 解決方案(至少在 2017 年)如下:

npm install restify-cors-middleware

然后在您的服務器 javascript 文件中:

var corsMiddleware = require('restify-cors-middleware');

var cors = corsMiddleware({
  preflightMaxAge: 5,
  origins: ['*']
});

var server = restify.createServer();

server.pre(cors.preflight);
server.use(cors.actual);

並添加任何其他適合您的選項。 我的用例是創建一個本地主機代理來解決開發過程中的瀏覽器 CORS 問題。 僅供參考,我使用 restify 作為我的服務器,但是我從服務器(和到服務器)的 POST 是使用 Axios 的。 我的偏好在那里。

用於 restify-cors-middleware 的 npm 列表

這對我來說就足夠了:

var server = restify.createServer();
server.use(restify.fullResponse());
server.get('/foo',  respond(req, res, next) {
   res.send('bar');
   next();
});

沒有必要server.use(restify.CORS()); 此外,似乎server.use()調用必須先於server.get()調用才能工作。

這對我有用restify 7

server.pre((req, res, next) => {

    res.header('Access-Control-Allow-Origin', req.header('origin'));
    res.header('Access-Control-Allow-Headers', req.header('Access-Control-Request-Headers'));
    res.header('Access-Control-Allow-Credentials', 'true');
    // other headers go here..

    if(req.method === 'OPTIONS') // if is preflight(OPTIONS) then response status 204(NO CONTENT)
        return res.send(204);

    next();

});

我使用的是 Restify 7.2.3 版本,這段代碼非常適合我。 您需要安裝 restify-cors-middleware 插件。

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

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

server.pre(cors.preflight)
server.use(cors.actual)
   const cors = require('cors');


   const server = restify.createServer();

   server.use(cors());

這對我有用

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

const cors = corsMiddleware({
  origins: ['*']
});

const server = restify.createServer();
server.pre(cors.preflight);
server.use(cors.actual);

server.get('/api/products', (request, response) => {
  response.json({ message: 'hello REST API' });
});

server.listen(3000, () => console.info(`port 3000`));

... 是一種蠻力解決方案,但您應該非常小心這樣做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM