node.js 使用restify时如何支持cors
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14338683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I support cors when using restify
提问by Kim
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?
我有一个使用 restify 模块创建的 REST api,我想允许跨源资源共享。最好的方法是什么?
回答by Jean-Michel Trayaud
The latest version of Restify provides a plugin to handle CORS.
最新版本的 Restify 提供了一个插件来处理 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']
}));
回答by Stephen Reid
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.
您必须设置服务器以设置跨源头。不确定是否有内置的 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();
}
);
I found this from this tutorial. http://backbonetutorials.com/nodejs-restify-mongodb-mongoose/
我从本教程中找到了这个。http://backbonetutorials.com/nodejs-restify-mongodb-mongoose/
回答by Cyrusmith
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);
});
回答by Pavel Nikolov
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
回答by techgyani
CORS Plugin is deprecated in favor of https://github.com/Tabcorp/restify-cors-middleware. (Source: https://github.com/restify/node-restify/issues/1091.)
CORS 插件已弃用,取而代之的是https://github.com/Tabcorp/restify-cors-middleware。(来源: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)
回答by MattC
MOST OF THE PREVIOUS ANSWERS ARE FROM 2013 AND USE DEPRECATED EXAMPLES! The solution (in 2017 at least) is as follows:
以前的大部分答案来自 2013 年,并使用已弃用的示例!解决方案(至少在 2017 年)如下:
npm install restify-cors-middleware
Then in your server javascript file:
然后在您的服务器 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);
And add whatever additional other options work for you. My use case was creating a localhost proxy to get around browser CORS issues during devolopment. FYI I am using restify as my server, but then my POST from the server (and to the server) is with Axios. My preference there.
并添加任何其他适合您的选项。我的用例是创建一个本地主机代理来解决开发过程中的浏览器 CORS 问题。仅供参考,我使用 restify 作为我的服务器,但是我从服务器(和到服务器)的 POST 是使用 Axios 的。我的偏好在那里。
回答by Giuseppe
If anyone comes across this as of Feb 2018 there seems to be a bug that's been introduced, I couldn't get the restify-cors-middlewareto work.
如果有人在 2018 年 2 月遇到这个问题,似乎已经引入了一个错误,我无法让它restify-cors-middleware工作。
I'm using this work around for now:
我现在正在使用这项工作:
server.pre((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
next();
});
回答by Mel
To enable CORS for basic authentication I did the following. It did not work until the .premethods were used instead of the .usemethods
为了启用 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);
回答by Lyman Lai
I do it like this on my restify base app:
我在我的 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());
you need to use restify.CORS.ALLOW_HEADERS.push method to push the header u want into restify first, then using the CORS middleware to boot the CORS function.
您需要先使用restify.CORS.ALLOW_HEADERS.push 方法将您想要的header 推送到restify 中,然后使用CORS 中间件启动CORS 功能。
回答by vedsmith92
This worked for me with restify 7
这对我有用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();
});

