0
0
Node.jsframework~5 mins

Request object properties in Node.js

Choose your learning style9 modes available
Introduction

The request object holds all the information about what a user sends to your server. It helps you understand and respond to their needs.

When you want to read data sent by a user in a web form.
When you need to check the URL or query parameters a user requested.
When you want to see headers like cookies or authentication tokens.
When you want to handle different HTTP methods like GET or POST.
When you want to access uploaded files or JSON data sent by the user.
Syntax
Node.js
req.propertyName
The request object is usually named 'req' in Node.js frameworks like Express.
You access properties directly to get information about the user's request.
Examples
Gives the full URL path the user requested.
Node.js
req.url
Tells you if the request is GET, POST, PUT, DELETE, etc.
Node.js
req.method
Accesses the content type header sent by the user.
Node.js
req.headers['content-type']
Contains data sent by the user in the request body (like form data or JSON).
Node.js
req.body
Sample Program

This simple Express server listens for POST requests to '/submit'. It reads the request method, URL, content-type header, and JSON body sent by the user. Then it sends back these details as a response.

Node.js
import express from 'express';
const app = express();
app.use(express.json());

app.post('/submit', (req, res) => {
  const method = req.method;
  const url = req.url;
  const contentType = req.headers['content-type'];
  const data = req.body;

  res.send(`Method: ${method}\nURL: ${url}\nContent-Type: ${contentType}\nData: ${JSON.stringify(data)}`);
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

Always use middleware like express.json() to parse JSON bodies before accessing req.body.

Headers are case-insensitive but usually accessed in lowercase in Node.js.

Request properties help you understand what the user wants so you can respond correctly.

Summary

The request object holds all details about what the user sends to your server.

You access properties like req.method, req.url, req.headers, and req.body to get this information.

Using these properties helps you build dynamic and responsive web servers.