1

My app.get('*') isn't being run and I have no idea why. I've tried using '/' as the route as well and I can't get anything to return. I have posted the code below.

const express = require('express');
const morgan = require('morgan');

const shoeRouter = require('./routes/shoeRouter');

const app = express();

// MIDDLEWARE
if (process.env.NODE_ENV === 'development') {
  app.use(morgan('dev'));
}

app.use(express.json());

// ROUTES
app.use('/api/shoes', shoeRouter);

app.use((err, res) => {
  return res.json({ errorMessage: err.message });
});

const path = require('path');

app.use(express.static(path.join(__dirname, '/../client/build')));

app.get('*', (req, res) => {
  res.send('Hello World');
});

module.exports = app;
Dylan L.
  • 1,243
  • 2
  • 16
  • 35

2 Answers2

2

The problem is probably your global error handler. You've registered a middleware function with two parameters which Express sees as a regular (req, res) => void middleware. It doesn't do any inspection on argument names.

To register a global error handling middleware, you need a function with at least 4 arguments

app.use((err, req, res, next) => {
  return res.json({ errorMessage: err.message });
});

See Writing error handler

Define error-handling middleware functions in the same way as other middleware functions, except error-handling functions have four arguments instead of three: (err, req, res, next)

Phil
  • 157,677
  • 23
  • 242
  • 245
-2

I think, You should put the app.get('*') before app.use('/api/...')

Ali Fakoor
  • 82
  • 2
  • 1
    Catch-all handlers should definitely be registered **last**. See [Order of router precedence in express.js](https://stackoverflow.com/q/32603818/283366) – Phil Mar 25 '22 at 05:28