How to Send HTML Response in Express: Simple Guide
In Express, you can send an HTML response using
res.send() by passing a string containing your HTML code. This method sets the correct content type automatically and sends the HTML to the client.Syntax
The basic syntax to send an HTML response in Express is using res.send() inside a route handler. You pass a string with your HTML content to res.send(). Express sets the Content-Type header to text/html automatically.
res: The response object from Express.send(): Method to send the response body.- HTML string: The HTML content you want to send.
javascript
app.get('/path', (req, res) => { res.send('<h1>Hello, world!</h1>'); });
Example
This example shows a complete Express server that sends a simple HTML page when you visit the root URL. It demonstrates how to use res.send() to deliver HTML content.
javascript
import express from 'express'; const app = express(); const port = 3000; app.get('/', (req, res) => { res.send(` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Express HTML Response</title> </head> <body> <h1>Welcome to Express!</h1> <p>This is an HTML response sent from Express.</p> </body> </html> `); }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });
Output
Server running at http://localhost:3000
When you visit http://localhost:3000 in a browser, you see a page with a heading "Welcome to Express!" and a paragraph below it.
Common Pitfalls
Some common mistakes when sending HTML responses in Express include:
- Forgetting to send a string and instead sending an object, which results in JSON response.
- Not including the full HTML structure, which can cause incomplete rendering in browsers.
- Using
res.sendFile()incorrectly when you want to send inline HTML.
Always ensure your HTML is a string and properly formatted.
javascript
/* Wrong: sending an object instead of HTML string */ app.get('/wrong', (req, res) => { res.send({ message: '<h1>Hi</h1>' }); // Sends JSON, not HTML }); /* Right: sending HTML string */ app.get('/right', (req, res) => { res.send('<h1>Hi</h1>'); // Sends HTML });
Quick Reference
Tips for sending HTML responses in Express:
- Use
res.send()with a string containing your HTML. - Express automatically sets the
Content-Typeheader totext/html. - Include full HTML structure for best browser compatibility.
- For sending HTML files, use
res.sendFile()instead.
Key Takeaways
Use res.send() with an HTML string to send HTML responses in Express.
Express sets the Content-Type header to text/html automatically when sending HTML strings.
Always send a string, not an object, to avoid sending JSON instead of HTML.
Include full HTML structure for proper rendering in browsers.
For sending HTML files, prefer res.sendFile() over res.send().