Sending Responses in Express

In Express, sending responses is how your server communicates with clients. You can send plain text, JSON, HTML, and even handle redirects and status codes.

Setting Up Express and Creating a Basic Server

  1. First, create a new Node.js project and install the Express package like we did for the previous tutorials.
  2. npm init
    npm install express
    
  3. Create a basic Express server as described in the previous guides.

Sending Plain Text Responses

  1. Use the res.send() method to send plain text responses.
app.get('/text', (req, res) => {
    res.send('This is a plain text response.');
});
  

Sending JSON Responses

  1. Send JSON responses using res.json().
app.get('/json', (req, res) => {
    const data = { message: 'This is a JSON response.' };
    res.json(data);
});
  

Sending HTML Responses

  1. Send HTML responses using res.send() or res.sendFile().
app.get('/html', (req, res) => {
    const htmlContent = '

This is an HTML response

'; res.send(htmlContent); });

Redirecting Responses

  1. Redirect to other routes or external URLs using res.redirect().
app.get('/redirect', (req, res) => {
    res.redirect('/html');
});
  

Handling Status Codes

  1. Use res.status() to set the HTTP status code for responses.
app.get('/not-found', (req, res) => {
    res.status(404).send('Not Found');
});
  

Streaming Responses

  1. Stream large files or data using res.write() and res.end().
app.get('/stream', (req, res) => {
    res.write('Streaming data...');
    setTimeout(() => {
        res.end();
    }, 2000);
});
  

Error Handling

  1. Handle errors in route handlers, and use next(err) to pass them to error-handling middleware.

app.get('/error', (req, res, next) => {
    const error = new Error('This is an error');
    next(error);
});

app.use((err, req, res, next) => {
    console.error(err.message);
    res.status(500).send('Internal Server Error');
});