0
0
Expressframework~5 mins

res.send for general responses in Express

Choose your learning style9 modes available
Introduction

res.send is used to send a response back to the client in a simple way. It helps your server talk to the browser or app by sending text, HTML, or data.

When you want to send a simple message or text back to the user.
When you want to send HTML content as a response.
When you want to send JSON or other data formats quickly without extra setup.
When you want to end the response and tell the client you are done sending data.
Syntax
Express
res.send(body)

body can be a string, a buffer, an object, or an array.

If you send an object or array, Express automatically converts it to JSON.

Examples
Sends a simple text message to the client.
Express
res.send('Hello World!')
Sends a JSON object. Express converts it to JSON format automatically.
Express
res.send({ message: 'Success' })
Sends HTML content that the browser will render as a heading.
Express
res.send('<h1>Welcome</h1>')
Sample Program

This simple Express server has two routes. The root route sends a plain text message. The /json route sends a JSON object. Both use res.send to send responses.

Express
import express from 'express';

const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.send('Hello from Express!');
});

app.get('/json', (req, res) => {
  res.send({ status: 'ok', message: 'This is JSON data' });
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});
OutputSuccess
Important Notes

Using res.send automatically sets the correct Content-Type header based on the data you send.

Calling res.send ends the response, so you should not call it more than once per request.

Summary

res.send sends a response back to the client easily.

It works with text, HTML, JSON, and more.

It automatically sets headers and ends the response.