Skip to main content

async handler , req, res , http method

Published 7 min readMarkdown

💡 What is this function?

It's a utility function commonly used in Express.js apps to handle errors in asynchronous route handlers.

Express doesn’t automatically catch errors in async functions (like async/await). So, instead of writing try/catch in every route, we wrap them with asyncHandler.


✅ Code Breakdown:

jsCopyEditfunction asyncHandler(requestHandler) {
    return function(req, res, next) {
        Promise.resolve(requestHandler(req, res, next))
        .catch(function(err) {
            next(err);
        });
    }
}

Let’s go step by step.


🧩 function asyncHandler(requestHandler)

This is a higher-order function – it takes another function (requestHandler, which is usually an async route handler) as input.


🧩 return function(req, res, next) { ... }

This returns a new middleware function with the standard Express parameters: req, res, and next.

So when you call asyncHandler(someAsyncRoute), it returns a new function that wraps that async route.


🧩 Promise.resolve(requestHandler(req, res, next))

Even if requestHandler is an async function (returns a Promise), we make sure it's treated as a promise here.

This lets us catch any rejections from the async function.


🧩 .catch(function(err) { next(err); })

If there's an error inside the async route, it will be caught here and passed to next(err), which will trigger Express’s error-handling middleware.


✅ Usage Example:

Without asyncHandler:

jsCopyEditapp.get('/user', async (req, res) => {
  const user = await getUser();  // If this throws an error, app will crash
  res.send(user);
});

With asyncHandler:

jsCopyEditimport { asyncHandler } from './utils/asyncHandler.js';

app.get('/user', asyncHandler(async (req, res) => {
  const user = await getUser();
  res.send(user);
}));

Now if getUser() fails, the error is caught and passed to Express's error middleware safely.


🔁 Summary

ConceptPurpose
asyncHandlerWraps async route handlers to auto-catch errors
Promise.resolve()Ensures the handler is treated as a Promise
.catch(next)Passes any error to the Express error handler
BenefitNo need to manually write try/catch in every async route

Let me know if you want a visual diagram or if you're curious how Express error handling works behind the scenes!

4o

You said:

what we write req.body or req.body() and is it means we are requesting data to be stored in the body or something else

ChatGPT said:

Great question! Let’s clear this up — this is something every backend dev wonders when starting with Express or APIs.


✅ What is req.body in Express?

  • req.body is a property, not a function — so you write:

      jsCopyEditreq.body
    

    ❌ Not req.body() (that would cause an error).


🧠 What does req.body mean?

  • It contains data sent by the client in the body of the request, usually from:

    • A form submission

    • A POST request with JSON

    • Any request with a payload (like POST, PUT, or PATCH)

You're not requesting data to be stored in the body — instead, you're reading what the client sent.


🧪 Example:

Say you send this POST request from the frontend:

jsCopyEditfetch('/login', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ username: 'kavin', password: '1234' })
});

In your Express backend, you can access it like this:

jsCopyEditapp.post('/login', (req, res) => {
  console.log(req.body); 
  // 👉 Output: { username: 'kavin', password: '1234' }
});

❗ Important: Middleware is required!

To use req.body, you must use a body parser middleware, like:

jsCopyEditapp.use(express.json()); // to parse JSON body
app.use(express.urlencoded({ extended: true })); // for form data

Otherwise, req.body will be undefined.


🔁 Recap

TermMeans
req.bodyAccesses the body of the request (sent by client)
req.body()❌ Invalid — req.body is not a function
UsageMostly in POST, PUT, PATCH routes

Let me know if you'd like an example project using req.body, like a login or form handling route!

4o

You said:

we use req with post and res with get right ?

ChatGPT said:

That’s a super common misunderstanding when starting out — but here’s the truth:

❌ No, it's not that:

  • req is only for POST

  • res is only for GET


✅ Here's the correct understanding:

In any route (GET, POST, PUT, etc.), you always use both req and res.

  • req = the request object → holds data sent from the client (query, params, body, etc.)

  • res = the response object → used to send a response back to the client


🔁 You use both req and res in ALL HTTP methods:

🔹 GET Example:

jsCopyEditapp.get('/hello', (req, res) => {
  console.log(req.query); // 👈 reads query parameters
  res.send('Hello world!'); // 👈 sends response
});

🔹 POST Example:

jsCopyEditapp.post('/login', (req, res) => {
  console.log(req.body); // 👈 reads body (e.g., { username: 'kavin' })
  res.json({ message: 'Login success' }); // 👈 sends JSON response
});

✅ Summary Table

HTTP MethodUsed forreq used for...res used for...
GETFetching datareq.query, req.paramsres.send, res.json
POSTSending datareq.bodyres.send, res.status
PUT/PATCHUpdating datareq.body, req.paramsres.send, res.json
DELETEDeleting datareq.paramsres.send

If it helps, think of it like:

📨 req is what the client sends,
📤 res is what your server replies with.

Let me know if you want me to give you a quick mini-project using GET and POST routes to practice!

4o

You said:

yeah can you also explain how we use the res, and req for the client and server bnoth

ChatGPT said:

Absolutely! Let’s walk through how req and res work on both the client and server side — this will help you see the big picture of how data flows in a web app. 🚀


⚙️ Roles of req and res

🔵 Term🎯 What it means
reqThe request object sent by the client
resThe response object sent by the server back to the client

So in simple terms:

👉 The client sends a request (req)
👉 The server processes it and sends a response (res)


🧠 Client Side (Frontend) — Making a Request

In frontend (like using JavaScript with fetch, Axios, etc.), you send a request using fetch() like this:

🧪 Example:

jsCopyEdit// Client code (e.g., inside a browser)
fetch('http://localhost:3000/login', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ username: 'kavin', password: '1234' })
})
.then(res => res.json()) // 👈 reading the server's response
.then(data => console.log(data))
.catch(err => console.error(err));

🔍 Here:

  • You’re sending a request (req) to the server.

  • You use res.json() to read the server’s response (res).


🖥️ Server Side (Backend with Express)

Now on the server, you receive the request, process it, and send back a response.

Example Express route:

jsCopyEditapp.post('/login', (req, res) => {
  const { username, password } = req.body; // 👈 reading the client's request
  console.log('Client sent:', username, password);

  // process... maybe check credentials

  res.json({ success: true, message: 'Welcome, ' + username }); // 👈 sending response
});

🔁 Full Flow:

textCopyEditClient (Browser)                  Server (Express.js)
-----------------                --------------------
     req: fetch()  ------------>     app.post('/login', (req, res) => {})
         with body: JSON                 └── req.body reads data

                                     do something...

     <------------  res.json(...)       res sends data back to client
         with message: JSON

🛠️ Typical Use of req and res

ActionWhat you use
Client sends data (form, login)fetch() or Axios (sends the request)
Server reads itreq.body, req.query, or req.params
Server sends back resultres.send(), res.json(), res.status()
Client receives response.then(res => res.json()) or .text()

✅ Quick Real Example (You can try this locally!)

Server: server.js

jsCopyEditimport express from 'express';
const app = express();
app.use(express.json());

app.post('/greet', (req, res) => {
  const { name } = req.body;
  res.json({ message: `Hello, ${name}!` });
});

app.listen(3000, () => console.log('Server running on port 3000'));

Client: in HTML/JS or browser console

jsCopyEditfetch('http://localhost:3000/greet', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Kavin' })
})
.then(res => res.json())
.then(data => console.log(data)); // 👉 Output: { message: 'Hello, Kavin!' }

About the author

  • 💻 Software Developer | 🚀 Building next-gen digital platforms 🔭 Currently working on a fan-influencer interaction startup 💡 Passionate about scalable systems, DSA, system design & product thinking 📚 Electrical Engineering @NIT JSR | 2nd Year ✨ Learning in public | Sharing my journey in tech & startups

No comments yet. Be the first to comment.