允许CORS REST请求到Heroku上的Express / Node.js应用程序

我在node.js的快速框架上编写了一个REST API,这个框架适用于Chrome中js控制台的请求和URL栏等等。我现在试图让它适用于来自另一个应用程序的请求域(CORS)。

第一个由javascript前端自动创build的请求是/ api / search?uri =,并且在“预检”选项请求中显示为失败。

在我的快速应用程序中,我添加CORS标题,使用:

var allowCrossDomain = function(req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With'); // intercept OPTIONS method if ('OPTIONS' == req.method) { res.send(200); } else { next(); } }; 

和:

 app.configure(function () { app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(allowCrossDomain); app.use(express.static(path.join(application_root, "public"))); app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); 

从Chrome控制台,我得到这些标题:

请求URL:http://furious-night-5419.herokuapp.com/api/search?uri = http%3A%2F%2Flocalhost%3A5000%2Fcollections%2F1%2Fdocuments%2F1

请求方法:选项

状态码:200 OK

请求头

 Accept:*/* Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3 Accept-Encoding:gzip,deflate,sdch Accept-Language:en-US,en;q=0.8 Access-Control-Request-Headers:origin, x-annotator-auth-token, accept Access-Control-Request-Method:GET Connection:keep-alive Host:furious-night-5419.herokuapp.com Origin:http://localhost:5000 Referer:http://localhost:5000/collections/1/documents/1 User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.56 Safari/536.5 

查询string参数

 uri:http://localhost:5000/collections/1/documents/1 

响应头

 Allow:GET Connection:keep-alive Content-Length:3 Content-Type:text/html; charset=utf-8 X-Powered-By:Express 

这看起来像是缺乏由API应用程序发送正确的标题吗?

谢谢。

我在一个干净的ExpressJS应用程序上检查了你的代码,它工作得很好。

尝试将您的app.use(allowCrossDomain)移到configuration函数的顶部。

为了支持Cookie,您需要这个行xhr.withCredentials = true;

mdn docs xhr.withCredentials

在Express服务器之前添加此块的所有其他

 `app.all('*', function(req, res, next) { var origin = req.get('origin'); res.header('Access-Control-Allow-Origin', origin); res.header("Access-Control-Allow-Headers", "X-Requested-With"); res.header('Access-Control-Allow-Headers', 'Content-Type'); next(); });` 

对于大多数浏览这个问题的人来说,情况并非如此,但是我也遇到了完全相同的问题,解决scheme与CORS无关。

原来,JSON Web Token秘密string没有在环境variables中定义,所以令牌不能被签名。 这导致任何POST请求依赖于检查或签署令牌来获取超时并返回503错误,告诉浏览器在CORS中有什么问题,事实并非如此。 在Heroku中添加环境variables解决了这个问题。

我希望这可以帮助别人。