Nearby lessons
5 of 14π§© How to Render JSON and HTML in Express JS
π What is Response Rendering?
π‘ Understanding Response Rendering in Express.js
Express allows us to send different types of responses to the client β including HTML and JSON data.
Using the res.send() method, we can easily render both.
This feature is useful for building APIs (sending JSON) or creating simple web pages (sending HTML).
π§± Step 1: Rendering HTML in Express
We can directly send HTML code inside the res.send() method.
Express automatically sets the Content-Type header to text/html.
Let's look at an example that displays an HTML response with links between two routes (/ and /about).
Express.js Server
var express = require('express'); var app = express(); app.get('/', (req, res) => { res.send(` <h1>Welcome To CodingsPoints</h1> <a href='/about'>Go to About Page</a> `); }); app.get('/about', (req, res) => { res.send(` <h1>Welcome To About Page</h1> <a href='/'>Go to Home Page</a> `); }); app.listen(8080, () => { console.log("Server running at http://localhost:8080"); });
βοΈ Explanation: Rendering HTML
- res.send() β Sends an HTML response to the client.
- You can include
<h1>,<a>, or any HTML tag. - Express automatically sets
Content-Typeastext/htmlwhen sending HTML strings. - Useful for sending quick HTML-based responses for small apps or testing routes.
π¦ Step 2: Rendering JSON in Express
Express can also send JSON data directly using the same res.send() method.
If you pass an object or array, Express automatically sets Content-Type to application/json.
Letβs explore examples for both single and multiple JSON objects.
Express.js Server
var express = require('express'); var app = express(); app.get('/', (req, res) => { res.send({ name: "Codings Points", year: 2025 }); }); app.get('/about', (req, res) => { // Array of objects res.send([ { name: "Codings", year: 2025 }, { name: "Points", year: 2026 }, { name: "Codings Points", year: 2027 } ]); }); app.listen(8080, () => { console.log("Server running at http://localhost:8080"); });
π Explanation: Rendering JSON
- res.send(object) β Sends a JSON response automatically.
- res.send(array) β Sends an array of JSON objects.
- Express detects the data type and sets
Content-Typetoapplication/json. - Ideal for building RESTful APIs that return structured data.