Node module named dishRouter.js implements the Express router for the /dishes/:dishId REST API endpoint.

index.js

const express = require('express');
const http = require('http');
const morgan = require('morgan');
const hostname = 'localhost';
const port = 3000;
const app = express();
const dishRouter = require('./routes/dishRouter');
const bodyParser = require('body-parser');

app.use(morgan('dev'));
app.use(bodyParser.json()); //parse the json in the body
app.use('/dishes/:dishId', dishRouter);
app.use(express.static(__dirname + '/public'));

app.use((req, res, next) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/html');
  res.end('<html><body><h1>This is an express server</h1></body></html');
});

const server = http.createServer(app);

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}`)
});

dishRouter.js

const express = require('express');
const bodyParser = require('body-parser');
const dishRouter = express.Router();

dishRouter.use(bodyParser.json());
dishRouter.route('/')

  .all((req, res, next) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/html');
    next();
  })

  .get((req, res, next) => {
    res.end('Will send details of the dish: ' + req.params.dishId + ' to you!');
  })

  .post((req, res, next) => {
    res.write('Updating the dish: ' + req.params.dishId + '\n');
    res.end('Will update the dish: ' + req.body.name +
      ' with details: ' + req.body.description);
  })

  .put((req, res, next) => {
    res.end(req.params.dishId + ' Will update the dishId and dish: ' + req.body.name + 'with details: ' + req.body.description);
  })

  .delete((req, res, next) => {
    res.end('Deleting the dishId: ' + req.params.dishId);
  });

module.exports = dishRouter;

When sending a GET request to localhost:3000/dishes/28, the following response is sent:

Will send details of the dish: undefined to you!

But what I need is Will send details of the dish:28 to you!, and I am unable to solve the problem.

I also need the same response for the other method calls.

1

There are 1 best solutions below

3
On BEST ANSWER

When you store your Router in dishRouter, you need to tell it to inherit params from parents.

...
const dishRouter = express.Router({ mergeParams: true });
...

Express document