TheBrahminCoder - How to get Data from routes in express JS
There are two ways to get data from routes in Express.js:
- GET requests: You can get data from GET requests by using the
req.queryobject. This object contains all of the query parameters that were passed in the URL. For example, if you have a route that is defined as/users?name=John&age=25, you can get the value of thenamequery parameter by using the following code:
Code snippet
const name = req.query.name;
- POST requests: You can get data from POST requests by using the
req.bodyobject. This object contains the body of the POST request, which is usually in JSON format. For example, if you have a POST request that is defined as/users, and the body of the request is{"name": "John", "age": 25}, you can get the value of thenameproperty by using the following code:
Code snippet
const name = req.body.name;
Here is an example of how to get data from routes in Express.js:
Code snippet
const express = require("express");
const app = express();
app.get("/users", (req, res) => {
const name = req.query.name;
const age = req.query.age;
res.send(`Your name is ${name} and you are ${age} years old.`);
});
app.post("/users", (req, res) => {
const name = req.body.name;
const age = req.body.age;
res.send(`Your name is ${name} and you are ${age} years old.`);
});
app.listen(3000);
This code will create two routes:
/users: This route will get thenameandagequery parameters from the URL and send them back in the response./users: This route will get thenameandageproperties from the body of the POST request and send them back in the response.
To run this code, you can save it as a file called index.js and then run the following command in your terminal:
Code snippet
node index.js
This will start the Express server on port 3000. You can then test the routes by making requests to them in your browser. For example, you can make a GET request to http://localhost:3000/users?name=John&age=25 to get the name and age of John. You can also make a POST request to http://localhost:3000/users with the body {"name": "John", "age": 25} to get the name and age of John.
Comments
Post a Comment