How to add CORS headers to a Meteor app?

我的梦境 提交于 2019-12-17 18:29:00

问题


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");

});


来源:https://stackoverflow.com/questions/15959501/how-to-add-cors-headers-to-a-meteor-app

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!