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

我已经在用于node.js的快速框架上编写了REST API,该API可以处理来自Chrome中的js控制台和URL栏等的请求。现在,我试图使其适用于来自另一个应用程序的请求域(CORS)。


由javascript前端自动发出的第一个请求是对/ api / search?uri =的请求,并且似乎在“预检” OPTIONS请求中失败。


在我的快速应用中,我使用以下方法添加了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控制台中,我得到了以下标题:


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


请求方法:OPTIONS


状态码: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

查询字符串参数


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应用程序发送的标题不正确吗?


谢谢。


慕森王
浏览 610回答 3
3回答

拉风的咖菲猫

我已经在干净的ExpressJS应用上检查了您的代码,它正常工作。尝试将您app.use(allowCrossDomain)移至配置功能的顶部。

泛舟湖上清波郎朗

为了支持带有凭据的Cookie,您需要此行 xhr.withCredentials = true;mdn docs xhr.withCredentials在Express Server中,在所有其他块之前添加此块`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();});`

海绵宝宝撒

对于大多数浏览此问题的人来说,情况可能并非如此,但我也遇到了同样的问题,解决方案与无关CORS。事实证明,string在环境变量中未定义JSON Web令牌机密,因此无法对令牌进行签名。这会导致任何POST依赖于检查或签名令牌以获取超时并返回503错误的请求,从而告诉浏览器出了点问题CORS,事实并非如此。在Heroku中添加环境变量解决了该问题。我希望这可以帮助别人。
打开App,查看更多内容
随时随地看视频慕课网APP