Search code examples
node.jsnode-request

Node not redirecting to Page Not found 404


If I go to http://localhost:4000/asdfasd I should be seeing my page not found and my console.log in the server, but I don't see either or.

APP.JS

const EXPRESS = require('express');
const BODY_PARSER = require('body-parser');
const PATH = require('path');

const APP = EXPRESS();

const ADMIN_ROUTES = require('./routes/admin');
const SHOP_ROUTES = require('./routes/shop');

APP.use(BODY_PARSER.urlencoded({ extended: false }));

APP.use('/admin', ADMIN_ROUTES);
APP.use(SHOP_ROUTES);

APP.use((req, res, next) => {
  console.log('page not found');
  res
    .status(404)
    .sendFile(PATH.join(__dirname, '../', 'views', 'not-found.html'));
});

APP.listen(4000);

Solution

  • Example code


    Express is not sending not-found.html because something higher up in your pipeline is handling your GET request to /asdfasd.

    In your situation, APP.use(SHOP_ROUTES) is handling your request because all requests, excluding those that start with /admin, are first being sent to SHOP_ROUTES.

    Here are some cases demonstrating why you do not see not-found.html:


    Case 1: You are using router.use() in your shop router and it is handling the request.

    In this example:

    /routes/shop.js

    router.use((req, res, next) => res.send('Something'))
    

    A request to /asdfasd will display the word "Something" on the page. Express will not go further down the pipeline because the request has been handled already.


    Case 2: You have an asynchronous function inside your shop router that does not use next().

    For example, if you are making a call to some API:

    /routes/shop.js

    // request-promise is an HTTP request client that returns a promise
    const rp = require('request-promise')
    
    router.use((req, res, next) => {
        rp.get('https://myapi.com/users')
            .then(response => res.json(response))
            .catch()
    })
    

    and your API request returns a status code of 400+ or 500+, your request is essentially stuck inside of this router.use() because you did not tell Express how to handle bad requests.

    You would have to use the next function as a callback inside of your .catch():

    router.use((req, res, next) => {
        rp.get('https://myapi.com/users')
            .then(response => res.json(response))
            .catch(next)
    })
    

    Case 3: You have a dynamic route inside of your shop router, ex. /:word.

    If in your SHOP_ROUTES, you have a dynamic route, like the one below:

    /routes/shop.js

    router.get('/:word', (req, res, next) => res.send(req.params.word))
    

    Any request to / that is not already handled by a preceding route will be handled by this one.