Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 views
in Technique[技术] by (71.8m points)

node.js - Send additional http headers with Express.JS

I have a few static pages served with Express.JS. The setup is easy:

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:

app.get('/', function(req, res){
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.send('Hello World');
});

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...