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).

Example02
Loading editor…

βš™οΈ 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-Type as text/html when 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.

Example04
Loading editor…

πŸ“˜ 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-Type to application/json.
  • Ideal for building RESTful APIs that return structured data.

🧠 Test Your Knowledge

5 Questions
Progress: 0 / 5