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.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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();
})
})
回答2:
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");
});