Exploring req.params, req.query, and req.body: A Simple Explanation

Exploring req.params, req.query, and req.body: A Simple Explanation

ยท

2 min read

In Express, how many ways are there to send data from the client side to the server side?

  1. req.body: Use this when you want to submit a form or any sensitive data to the server without making it public. This is the preferred method.

  2. req.params: Use this when you want to send data to the server as a placeholder, like when you request information about a specific user from the server throught url then this method prefer to use.
    for example:- http://localhost:4000/user/25
    In this example, you request a user with the ID of 25 by using a placeholder in the URL.

  3. req.query: Use this method when have to take input from user in the form of key-value pair. Mostly this is used to search something.To us this we have write URL and modify that.

    For-example:- http://localhost:4000/users?name=Rim

    req.query extract the part of url from the question mark. What ever we write after the question mark this seems as query parameter.

params or parameter are use to get or set the dynamic information to the user Side.To handle all these in request in backend side first you have to Create a route.

const express = require("express");
const app = express();
const router = express.Router();


const PORT = 4004;
try{
    app.listen(PORT || 4004, ()=>{
        console.log(`๐Ÿ›ž Server Running on Port: ${PORT}`);
    })
} catch(error){
    console.log("Failed to start Server", error);
}
// in this route you will get the all the formdata that you send on this url
//http://localhost:4000/home/
router.post("/home", (req,res)=>{
    const b = req.body
    res.send(b)
})

To send and receive data on the backend, you just need to modify your route. Suppose you want to send the user's ID to the user page. You simply modify the API URL by adding a ":" followed by the key name of the item you want to send, like "id." So your modified URL should be: http://localhost:4000/user/:id


// in this route you will get the all the params that you send on this url
//http://localhost:4000/home/
router.post("/user/:", (req,res)=>{
    const b = req.body
    res.send(b)
})

Suppose you want to search for something. You need to modify your API to use req.query. You just have to add a "?" right after the API endpoint where you want to search. Let's say you have a page named Search where you want to find whatever the user enters. You would modify your API like this: http://localhost:4000/search?name=rim

Everything you pass after "?" is sent as a query parameter in key-value form.
Use this data as needed.

Thatโ€™s All
Happy Coding'
๐Ÿ˜Š๐Ÿ˜Š

ย