Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First request to node.js app on Windows Azure with MongoDB yields 400 Bad Request

I'm using Windows Azure to deploy a node.js application that I've written that exposes a fairly simple REST CRUD api to clients. Its hosted in a Windows Azure Website and uses MongoDB through the Windows Azure store with mongoose. The requests I'm making to the service are JSON and the responses are JSON (not sure that matters but others have talked about 400 responses to requests with a Content-Type of application/json)

On the first access in a long while, the application returns 400 Bad Request without fail. As long as I keep the application "warm" by hitting it frequently (at least once a minute or so) - I never seem to get this again.

It doesn't matter on the hosting scaling setting - I get the same thing on the free tier as in reserved mode.

Anyone else seen this?

like image 716
outside2344 Avatar asked Nov 12 '22 09:11

outside2344


1 Answers

In order to guarantee access to any connection in node.js, you have to put all code that requires a connection inside of the callback. The way that mongoose exposes this connection is through an event. When the event 'open' is called by the mongoose connection, then you have access to a database connection.

I.E.

mongoose.connect('details');

mongoose.on('open', function () {
  var connection = mongoose.connection;

  // Do things with your connection here
  doThings(connection);
});

function doThings(connection) {
  app.get(...);
}
like image 62
cptroot Avatar answered Nov 14 '22 21:11

cptroot