Categories
JavaScript Answers Nodejs

How to get the ID parameter from the URL with Express and Node.js?

Spread the love

Sometimes, we want to get the ID parameter from the URL with Express and Node.js.

In this article, we’ll look at how to get the ID parameter from the URL with Express and Node.js.

How to get the ID parameter from the URL with Express and Node.js?

To get the ID parameter from the URL with Express and Node.js, we can get it from the req.params object.

For instance, we write:

const express = require('express')
const app = express()
const port = 3000

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

app.get('/user/:id/docs', (req, res) => {
  const { id } = req.params;
  res.send(id)
});

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

to add the /user/:id/docs route with:

app.get('/user/:id/docs', (req, res) => {
  const { id } = req.params;
  res.send(id)
});

':id' is the placeholder for the id URL parameter.

We get the ID value from req.params.

Therefore, if we go to /user/1/docs, we see 1 returned as the response.

Conclusion

To get the ID parameter from the URL with Express and Node.js, we can get it from the req.params object.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *