允许CORS REST请求到express / node.js应用程序

我是node.js / express的新手。 我看到这篇文章( 允许CORS REST请求到Heroku上的Express / Node.js应用程序 ),但提议的解决scheme不起作用。

我只是打电话给mapquest API来获取一些数据来玩。

这里是我的server.js的一部分:

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) { console.log('hit options'); res.send(200); } else { next(); } }; app.configure(function(){ console.log('configuring app'); app.use(allowCrossDomain); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(__dirname + '/public')); //app.use(express.static(path.join(application_root, "public"))); app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); /** * Main route */ app.get('/', function (req, res, next) { console.log("getting /"); Project.findAll() .success(function (projects) { res.render('index', { projects: projects }); }) .error(next); }); 

这里是我的客户端main.js的一部分:

  $('#spec').click(function(ev){ var form = $(this); $.ajax({ url: "http://www.mapquestapi.com/geocoding/v1/address?key=<mykey>" , type: 'POST' , datatype: 'json' , contentType: 'json' , data: { location : { "postalCode":"99999" } , options : { thumbMaps : false} } , success: function(resp){ $('#mapdata').html(resp); } , error : function(resp){ $('#mapdata').html(resp); } }); }); 

这是我在chrome dev窗口中的请求标题:

 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:accept, origin, content-type Access-Control-Request-Method:POST Connection:keep-alive Host:www.mapquestapi.com Origin:http://localhost:3000 Referer:http://localhost:3000/ User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.43 Safari/537.31 

这里是响应标题:

允许:TRACE,OPTIONS Content-Length:0date:Sun,07 Apr 2013 03:18:48 GMT服务器:Apache-Coyote / 1.1

这里是错误信息:

 Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin. 

当目标HTTP服务器启用时,CORS才起作用。 在你的情况下,目标HTTP服务器是www.mapquestapi.com 。 在您自己的服务器中启用CORS不会启用MapQuest服务器上的CORS。

我想你或者需要检查MapQuest是否支持JSONP(通过MapQuest的示例代码来判断,很可能),或者使用MapQuest提供的地理编码API 。

如果这两个select不是一个选项,您剩下的唯一select是在您自己的服务器上创build一个代理,通过这个代理可以向MapQuest服务器发送请求(您的服务器将向MQ服务器请求数据并将其发回到您的客户代码)。