The first request for a node.js application on Windows Azure with MongoDB gives 400 Bad Request

I use Windows Azure to deploy the node.js application that I wrote, which provides a fairly simple REST CRUD api for clients. It is hosted on the Windows Azure website and uses MongoDB through the Windows Azure Store with mongoose. The requests I make for the service are JSON, and JSON responses (not sure if the questions, among others, spoke of 400 responses to requests with Content-Type of application / json)

At first access for a long time, the application automatically returns 400 Bad Request. As long as I keep the application warm, often pressing it (at least once per minute), I never get it again.

It doesn’t matter when setting up host scaling. I get the same thing at the free level as in the reserved mode.

Has anyone else seen this?

+5
source share
2 answers

To guarantee access to any connection in node.js, you must put all the code requiring the connection inside the callback. The way the mongoose provides this connection is an event. When the "open" event is raised by the mongoose connection, you have access to the database connection.

those.

mongoose.connect('details');

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

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

function doThings(connection) {
  app.get(...);
}
+1
source

It would be helpful if you had a snippet of code, but I assume that your connection with mongo is asynchronous, and your site serves the request before the connection is really open.

. : https://github.com/ntotten/azure-mongo-sample

, mongoose , . .

app.js:

/**
 * Module dependencies.
 */

var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path');

var TaskList = require('./routes/tasklist');
var taskList = new TaskList(process.env.CUSTOMCONNSTR_MONGOLAB_URI);

...

tasklist.js:

var mongoose = require('mongoose')
  , task = require('../models/task.js');


module.exports = TaskList;


function TaskList(connection) {
  mongoose.connect(connection);
}

...
0

All Articles