Adding the below middleware (and possibly rendering a self-defined error page) makes Express give the 404 error when all the routes provided before it does not match the current URL. If this middleware is added before a valid route, that route will be blocked and 404 error will be returned.
1 | //404 Not Found Middleware |
Async Issue
I met with an async issue when adding this middleware when doing the issue tracker fCC project.
1 | //Routing for API |
It looks like the api routes are added before 404 middleware, but the apiRoutes function needs to build a database connection before adding the routes:
1 | /**apiRoutes*/ |
Because of this delay, the traffic is caught by the 404 middleware instead, and I always get a 404 error when making a request to /api/issues/:project.
To solve this problem, I put the apiRoutes(app) just before app.listen, and put the 404 middleware INSIDE the callback of the db connection. This means all the api routes will be finished before the 404 middleware is added.
chai-http routes
When running integration test (functional test) with chai.request(app), because the request is sent right after the app is initiated, the api routes are not properly loaded either:
1 | test('Every field filled in', function (done) { |
This is how the code provided by fCC solves the problem:
1 | if(process.env.NODE_ENV==='test') { |
It waits for 3.5 seconds for the test to start, to ensure that the tests are run upon a fully loaded server.