简体   繁体   中英

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

I am new to node.js/express. I saw this post ( Allow CORS REST request to a Express/Node.js application on Heroku ), but the proposed solution did not work.

I am just making a call to mapquest api to get some data to play around with.

Here is part of my 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);
});

And here is part of my client-side 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);
        }
    });
  });

Here are my request headers in chrome dev window:

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

And here are response headers:

Allow:TRACE, OPTIONS Content-Length:0 Date:Sun, 07 Apr 2013 03:18:48 GMT Server:Apache-Coyote/1.1

And here is the error message:

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

CORS only works when the targetted HTTP server has it enabled. In your case, the targetted HTTP server is www.mapquestapi.com . Enabling CORS in your own server isn't going to enable CORS on the MapQuest server.

I think you either need to check if MapQuest supports JSONP (judging by this example code from MapQuest that could very well be), or perhaps use the geocoding API that MapQuest provides.

If those two alternatives aren't an option, the only option you have left is to create a proxy on your own server via which you can send requests to the MapQuest server (your server would request the data from the MQ servers and send it back to your client code).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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