Home > Blockchain >  get request not working in Node.JS and express
get request not working in Node.JS and express

Time:03-25

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;

CodePudding user response:

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)

CodePudding user response:

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

  • Related