node.js 使用 Express.JS 发送额外的 http 标头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14171899/
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
Send additional http headers with Express.JS
提问by csg
I have a few static pages served with Express.JS. The setup is easy:
我有几个与 Express.JS 一起使用的静态页面。设置很简单:
var app = express();
app.configure(function(){
app.use(express.static(path.join(application_root, "StaticPages")));
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
I want the response to include an addittional http header (Access-Control-Allow-Origin:*). Where should it be placed? I tried the below sample, but of course the header appears only on the default page:
我希望响应包含一个附加的 http 标头(Access-Control-Allow-Origin:*)。应该放在哪里?我尝试了以下示例,但当然标题仅出现在默认页面上:
app.get('/', function(req, res){
res.setHeader("Access-Control-Allow-Origin", "*");
res.send('Hello World');
});
Thanks.
谢谢。
回答by Mattias
I tried the below sample, but of course the header appears only on the default page
我尝试了下面的示例,但当然标题只出现在默认页面上
Yes, that is because you defined it just for the GET /route and not for the other paths. You should use a middleware instead.
是的,那是因为您只是为GET /路线而不是其他路径定义了它。您应该改用中间件。
If you wish to set the header for all requests:
如果您希望为所有请求设置标头:
app.configure(function(){
app.use(function(req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
return next();
});
app.use(express.static(path.join(application_root, "StaticPages")));
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
If you just want to do it for the static folders, there is no general method. You can probably change the express.static(which comes from connect.static). Another way to do it is to match urls and set the header if the url is matched.
如果你只是想对静态文件夹做,没有通用的方法。您可能可以更改 express.static(来自connect.static)。另一种方法是匹配 url 并在 url 匹配时设置标题。
app.configure(function(){
app.use(function(req, res, next) {
var matchUrl = '/StaticFolder';
if(req.url.substring(0, matchUrl.length) === matchUrl) {
res.setHeader("Access-Control-Allow-Origin", "*");
}
return next();
});
app.use(express.static(path.join(application_root, "StaticPages")));
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
NOTE: that the middleware need to be before the routes to make effect, in other words you can't put the middleware after the static middleware.
注意:中间件必须在路由之前才能生效,也就是说你不能把中间件放在静态中间件之后。
回答by David Casier
Another way :
其它的办法 :
app.use(express.static(
path.join(application_root, "StaticPages"),
{
setHeaders: (res) => {
res.setHeader('Access-Control-Allow-Origin', '*')
}
}
))

