Overview
When you are working on creating REST API endpoints using Node.js, Express, and TypeScript, you might come across the need to utilize request parameters and query parameters. While both of these parameters are used for similar purposes, they are not the same. I’ll discuss the difference between Request Parameters and Query Parameters, I will also add code examples and the ideal time to use query parameters and request parameters.
They are both used to pass data to the server. However, they are used in different ways. request.params is used to pass parameters through the URL path, while request.query is used to pass parameters through the URL query string.
Using Request Parameters
Request parameters are used to send data to the server through the URL path. An example of a URL with a request parameter would look like this: http://127.0.0.1:5001/api/users/123. In this example, "123" is the request parameter. You can access request parameters using the request.params object. Here's an example code snippet:
app.get('/api/users/:id', (req, res) => {
const userId = req.params.id;
// Do something with userId
});
Here, we’re using a GET request to retrieve a user’s information by their ID. We’re passing the ID as a request parameter through the URL path, and we’re accessing it using request.params.id.
Using Query Parameters
Query parameters are used to send data to the server through the URL query string. An example of a URL with a query parameter would look like this: http://127.0.0.1:5001/api/users?id=123. In this example, "id" is the query parameter key, and "123" is the query parameter value. You can access query parameters using the request.query object. Here's an example code snippet:
app.get('/api/users', (req, res) => {
const userId = req.query.id;
// Do something with userId
});
In this example, we’re using a GET request to retrieve a user’s information by their ID. We’re passing the ID as a query parameter through the URL query string, and we’re accessing it using request.query.id.
Query Parameters vs. Request Parameters
Query parameters are ideal for filtering data or passing optional parameters to an API endpoint. For example, if you’re building an API endpoint that returns a list of users, you might want to filter the results by age, gender, or location. You can achieve this by using query parameters.
Request parameters are ideal for passing mandatory parameters to an API endpoint. For example, if you’re building an API endpoint that returns a user’s information by their ID, you’ll want to pass the ID as a request parameter.
'WEB' 카테고리의 다른 글
PHP 기본 시간대(timezone) (0) | 2021.08.09 |
---|---|
[Facebook] Where can I find my Facebook application id and secret key? (0) | 2021.02.14 |
[Facebook] 2020 Updated: How to get Facebook application id and secret key? (0) | 2021.02.14 |
[Facebook] Facebook Access Token for Pages (0) | 2021.02.14 |
[JS] Declare multiple module.exports in Node.js (0) | 2020.12.25 |