How to add CORS headers to a Meteor app?

2019-01-17 16:52发布

How it is possible to add Access-Control-Allow-Origin: * header to all responses (in particular, I am interested for static files under /public/) in Meteor? I would need this so that external web apps can access data provides by my Meteor app. More information about enabling CORS is here.

标签: meteor cors
2条回答
forever°为你锁心
2楼-- · 2019-01-17 17:37

There are two ways to go about this. One is to modify the meteor code and add it in (so that every file will be have this header). This might not be a great idea because you dont want every single file to have this. But if you do alter up do it with hooking into app

var app = __meteor_bootstrap__.app;
app.use(function(req,res) {
    res.setHeader('access-control-allow-origin', '*');
});

The other is to use a custom route with something like meteor router. This way you can control what files you want to have the headers in so its probably best to use something like this

Server side js:

Meteor.Router.add('/yourfile.txt', function() {
    this.response.setHeader('access-control-allow-origin', '*');

    var fs = Npm.require("fs");
    return fs.readFileSync("/public/yourfile.txt", "utf8");

});
查看更多
叼着烟拽天下
3楼-- · 2019-01-17 17:40

Here is a little snippet I wrote. You can use as an example in how to access meteor's core connect and modify headers, also a pretty good drop-in for every meteor project:

/**
 * HTTP Header Security
 *
 * enforce HTTP Strict Transport Security (HSTS) to prevent ManInTheMiddle-attacks
 * on supported browsers (all but IE)
 * > http://www.html5rocks.com/en/tutorials/security/transport-layer-security
 *
 * @header Strict-Transport-Security: max-age=2592000; includeSubDomains
 */

var connectHandler = WebApp.connectHandlers; // get meteor-core's connect-implementation

// attach connect-style middleware for response header injection
Meteor.startup(function () {
  connectHandler.use(function (req, res, next) {
    res.setHeader('Strict-Transport-Security', 'max-age=2592000; includeSubDomains'); // 2592000s / 30 days
    return next();
  })
})
查看更多
登录 后发表回答