404 handling middleware
In order to handle a 404 Not Found
response, let's add a 404 not found middleware. Let's write a test, ./test/heartbeat.js
; the content type returned should be JSON and the status code expected should be 404 Not Found
:
describe('vision heartbeat api', function(){ describe('when requesting resource /missing', function(){ it('should respond with 404', function(done){ request(app) .get('/missing') .expect('Content-Type', /json/) .expect(404, done); }) }); });
Now, add the following middleware to ./lib/middleware/notFound.js
. Here we export a function called index
and call res.json
, which returns a 404 status code and the message Not Found
. The next parameter is not called as our 404 middleware ends the request by returning a response. Calling next would call the next middleware in our Express stack; we do not have any more middleware due to this, it's customary to add error middleware and 404 middleware as the last middleware in your server:
exports.index = function(req, res, next){ res.json(404, 'Not Found.'); };
Now add the 404 not found middleware to ./lib/express/index.js
:
var express = require('express') , http = require('http') , config = require('../configuration') , heartbeat = require('../routes/heartbeat') , notFound = require('../middleware/notFound') , app = express(); app.set('port', config.get('express:port')); app.get('/heartbeat', heartbeat.index); app.use(notFound.index); http.createServer(app).listen(app.get('port')); module.exports = app;