Johan Wiström Johan Wiström - 3 months ago 14
Node.js Question

Node.js REST with Express not responding

I am new to Node and Express so my knowledge so far is limited. I have a setup with Node.js, Express and MongoDB. I am trying to route the request "localhost:3000/v1/user" by doing like this in my main .js-file:

MongoClient.connect(mongoUrl, function (err, db) {
if (err) {
console.log("Unable to connect to the mongoDB server. Error:", err);
} else {
//HURRAY!! We are connected. :)
console.log("Connection established to Mongo DB with connection string " + connection_string);


let port = process.env.NODE_PORT || 3000;
app.listen(port);
console.log('Server is now listening to port ' + port);

app.use(function(req, res){
req.db = db;
console.log("DB now available for all routes");
});


console.log("Using v1");
app.use('/v1', v1Route);
}
});


The connection to mongo gets established OK.
I have two routers in two separate files like this:

v1Route:

var express = require('express')
var router = express.Router();

const userRoute = require('./userRoute');

router.use('/user', userRoute);

module.exports = router;


userRoute:

const express = require('express');
var router = express.Router();

router.get('/', function(req,res){
console.log('fetching all users');
var collection = req.db.collection('user');
collection.find().toArray(function (err, result) {

if (err) {
console.log(err);
} else if (result.length > 0) {
console.log('Found entry');
res.status(200).send('Found:' + result[0].firstName + ' ' + result[0].lastName).end();
} else {
console.log('No document(s) found with defined "find" criteria!');
res.status(200).send('No document(s) found with defined "find" criteria!').end();
}
})


});

module.exports = router;


The problem is that nothing happens when I try to make the request "localhost:3000/v1/user". I get no error, just a browser that halts. When I send the request I get the log string "DB now available for all routes".

Answer

In your middleware function you're not calling next handler, so next middleware is not executed:

app.use(function(req, res, next) {
   req.db = db;
   console.log("DB now available for all routes");
   next();
});

You can check more documentation regarding writing middlewares on official express website: http://expressjs.com/en/guide/writing-middleware.html