Common Request and Response APIs

Learn common req and res APIs to read parameters and headers and control response content, status codes, and redirects.

🎯 Introduction

Routes and middleware provide the structure; the request object req and response object res do the work. By the end of this article, you will be able to read data sent by clients and choose an appropriate way to return results.


🧱 Meet req and res

For every incoming request, Express passes the request object req and response object res to the handler:

  • req: Holds information sent by the client, including parameters, the request body, and request headers.
  • res: Controls what you return to the client, including the status code, response headers, and response body.

These objects extend those provided by the native http module. They retain the underlying capabilities while making them much easier to use.


🛠 req: Read Client Data

Route Parameters and Query Parameters

We covered these in the routing article. Here is a quick review:

app.js
// Visit /users/1?keyword=Zhang
app.get('/users/:id', (req, res) => {
    console.log(req.params.id); // '1': a route parameter, as a string
    console.log(req.query.keyword); // 'Zhang': a query parameter
    res.send('ok');
});

Request Body: req.body

Data submitted with POST or PUT goes in the request body. Register express.json() first, then read it through req.body:

app.js
const app = express();

app.use(express.json());

app.post('/users', (req, res) => {
    console.log(req.body); // { name: 'Ming', age: 18 }
    res.send('Created successfully');
});

Request Headers: req.headers and req.get

Request headers carry information about the client and its identity, such as an authentication token or client type. There are two ways to read them:

app.js
app.get('/profile', (req, res) => {
    console.log(req.headers.token); // Option 1: property access, with lowercase keys
    console.log(req.get('User-Agent')); // Option 2: the case-insensitive get() method

    res.send('ok');
});
Keys in req.headers are normalized to lowercase, while req.get('Token') is case-insensitive. For individual headers, req.get() is often more convenient.

🛠 res: Control the Response

res.send and res.json

res.send() is a general-purpose response method. It sets Content-Type automatically based on the value you pass:

app.js
app.get('/text', (req, res) => {
    res.send('Hello'); // Sets text/html; charset=utf-8 automatically
});

app.get('/user', (req, res) => {
    res.send({ name: 'Ming' }); // Serializes to JSON and sets application/json
});

With the native http module, we had to call setHeader and JSON.stringify manually. Express handles those details for you, including the encoding needed to display non-ASCII text correctly.

When returning JSON, you can use the more explicit res.json(). It has the same effect as passing an object to res.send():

app.js
app.get('/user', (req, res) => {
    res.json({ name: 'Ming', age: 18 });
});

Set the Status Code with res.status

res.status() sets the status code and returns res itself, so you can chain calls:

app.js
app.post('/users', (req, res) => {
    // Return 201 to indicate successful resource creation
    res.status(201).json({ message: 'Created successfully' });
});

app.get('/users/99', (req, res) => {
    res.status(404).json({ message: 'User not found' });
});

Set Response Headers with res.set

Use res.set() for custom response headers—for example, to tell clients how long a response may be cached:

app.js
app.get('/config', (req, res) => {
    res.set('Cache-Control', 'max-age=3600');
    res.json({ theme: 'dark' });
});

Redirect with res.redirect

Send the client to another URL, often when moving an old page:

app.js
app.get('/old-page', (req, res) => {
    res.redirect('/new-page');
});

Visiting /old-page in the browser automatically redirects to /new-page.

Send only one response per request. Calling res.json() after res.send() causes a Cannot set headers after they are sent error. Use return where needed to ensure only one response branch executes.

🧰 Ways to Test Endpoints

You can open GET endpoints directly in a browser. For POST, PUT, and DELETE, use curl in your terminal:

# Send a POST request with JSON
curl -X POST http://localhost:3000/users -H "Content-Type: application/json" -d "{\"name\":\"Ming\"}"

# Send a GET request with query parameters
curl "http://localhost:3000/users/1?keyword=Zhang"

If you prefer a graphical interface, use an API testing tool such as Postman or Apifox.

API testing tools update their interfaces periodically, so button names and locations may differ in your version. The underlying process stays the same: choose the request method, enter the URL, and configure the headers and body. Follow the interface in the version you use.

❓ Questions and Answers

Q1: What is the difference between res.send() and res.json()?

Both return JSON when passed an object. The difference is intent and supported types: res.json() explicitly indicates JSON, while res.send() can also return strings, Buffers, and other types. For data endpoints, res.json() communicates the intent more clearly.

Q2: What if I call res.status(404) but forget res.json()?

res.status() only sets the status code; it does not finish the response. Without a response method afterward, the request hangs. Follow it with a method that ends the response, such as res.json() or res.send().

Q3: Do I need to convert numeric values in req.query?

Yes. Simple query values are strings, just like the route parameter values shown earlier: ?page=2 gives you '2'. Convert with Number() before doing arithmetic.

Q4: What if Chinese characters appear garbled in curl?

URL-encode Chinese characters in the request URL, or use --data-urlencode to let curl encode them. This is a client-side encoding issue in curl, rather than a problem with Express parsing.


🧪 Exercise

Write a GET /greet endpoint that reads the name query parameter. If present, return JSON { "message": "Hello, xxx" }. If name is missing, return status 400 with { "message": "Please provide the name parameter" }.

app.js
import express from 'express';

const app = express();

// Write your code here

app.listen(3000);

🎉 You can now work with requests and responses! Next, we will cover error handling so your server can respond gracefully when something goes wrong.