繁体   English   中英

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

[英]Allow CORS REST request to an express/node.js app

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

我只是打电话给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

以下是响应标头:

允许:跟踪,选项内容长度:0日期:太阳,2013年4月7日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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM