cross-origin resource sharing

I keep finding myself going over to the Enable CORS website to copy/paste their example code into my server-side.  They’ve saved me more than once.

Yet again today I was momentarily flummoxed over some seemingly-correct Javascript code in a PhoneGap project to fetch a json response from the server.

 $.getJSON(strURL, function(jsonData) {
  // Do nothing at this level but wait for the response
  }).done(function(jsonData) {
    // Do something upon success
  }).fail(function(XMLHttpRequest, textStatus, e) {
    $('#homeStatusParagraph').html('Lookup failed,
      status=[' + textStatus + '], error=[' + e + ']');
  }).always(function(jsonData) {
    // Do nothing here
 });

Interestingly, the fail() code section ran instead of the expected done() section.  At this point I then made the call manually to the server address represented in the strURL variable and it returned exactly what I thought it would, a json-formatted document.

The status returned from getJSON() was simply error and the returned e object was empty, not very useful for troubleshooting this.  What’s actually going on is that the client-side browser is blocking the inclusion of json fetched from another computer, presumably for security reasons.

Fortunately I’ve dealt with this before and inserted the code in green below to my Node.js server’s app.js file.

app.use(passport.initialize());
app.use(passport.session());
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept");
  next();
});
var routes = require("./routes/index");

This immediately fixed the problem and getJSON() on the client now happily worked, parsing the response from the server.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s