2018-10-12 15:37:13 -04:00
|
|
|
---
|
|
|
|
title: Get Route Parameter Input from the Client
|
|
|
|
---
|
2019-07-24 00:59:27 -07:00
|
|
|
# Get Route Parameter Input from the Client
|
2018-10-12 15:37:13 -04:00
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
---
|
|
|
|
## Problem Explanation
|
2019-07-02 07:05:15 +05:30
|
|
|
If someone tells you to build a GET or POST endpoint you would achieve the same using `app.get(...)` or `app.post(...)` accordingly.
|
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
|
|
|
|
---
|
|
|
|
## Hints
|
|
|
|
|
|
|
|
## Hint #1
|
2019-07-02 07:05:15 +05:30
|
|
|
|
|
|
|
In order to get route parameters from a POST request, the general format is as follows:
|
2018-10-12 15:37:13 -04:00
|
|
|
|
|
|
|
```javascript
|
2019-07-02 07:05:15 +05:30
|
|
|
app.post("/:param1/:param2", (req, res) => {
|
|
|
|
// Access the corresponding key in the req.params
|
|
|
|
// object as defined in the endpoint
|
|
|
|
var param1 = req.params.parameter1;
|
|
|
|
// OR use destructuring to get multiple paramters
|
|
|
|
var { param1, param2 } = req.params;
|
|
|
|
// Send the req.params object as a JSON Response
|
|
|
|
res.json(req.params);
|
2018-10-12 15:37:13 -04:00
|
|
|
});
|
|
|
|
```
|
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
|
|
|
|
---
|
|
|
|
## Solutions
|
|
|
|
|
|
|
|
<details><summary>Solution 1 (Click to Show/Hide)</summary>
|
2018-10-12 15:37:13 -04:00
|
|
|
|
2019-07-02 07:05:15 +05:30
|
|
|
```javascript
|
|
|
|
app.get("/:word/echo", (req, res) => {
|
|
|
|
const { word } = req.params;
|
|
|
|
res.json({
|
|
|
|
echo: word
|
|
|
|
});
|
|
|
|
});
|
|
|
|
```
|
2019-07-24 00:59:27 -07:00
|
|
|
</details>
|