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
- First, create a new Node.js project and install the Express package like we did for the previous tutorials.
- Create a basic Express server as described in the previous guides.
npm init
npm install express
Sending Plain Text Responses
- 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
- 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
- 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
- Redirect to other routes or external URLs using res.redirect().
app.get('/redirect', (req, res) => {
res.redirect('/html');
});
Handling Status Codes
- 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
- 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
- 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');
});