Node.js: Code Outside the Browser / HTTP Module-Creating a Web Server (No Express)

Sending HTML or JSON responses

πŸ“¦ Sending Structured Data (HTML & JSON)

Beyond plain text, you can send back HTML or JSON β€” the browser renders each one differently based on the Content-Type header you set.


πŸ“„ HTML Response

// index.js
import { createServer } from 'node:http';

const server = createServer((req, res) => {
  res.setHeader('Content-Type', 'text/html');
  res.end('<h1>Hello from HTML!</h1><p>This is a web page</p>');
});

server.listen(3000, () => {
  console.log('HTML Server running at <http://localhost:3000>');
});
  • Content-Type: text/html tells the browser to render the string as HTML, rather than showing the raw tags as plain text.

  • res.end(html) can take the content directly, so a separate res.write() call isn't needed here.

πŸ’» Terminal output:

HTML Server running at <http://localhost:3000>

🌐 Browser output β€” visiting http://localhost:3000 shows a rendered page:

Hello from HTML!

This is a web page

(The raw HTML sent was <h1>Hello from HTML!</h1><p>This is a web page</p> β€” the browser turns those tags into an actual heading and paragraph.)


🧾 JSON Response

// index.js
import { createServer } from 'node:http';

const server = createServer((req, res) => {
  res.setHeader('Content-Type', 'application/json');

  const data = {
    name: 'Varsha',
    course: 'Node.js',
    mood: 'Awesome'
  };

  res.end(JSON.stringify(data));
});

server.listen(3000, () => {
  console.log('JSON Server running at <http://localhost:3000>');
});
  • Content-Type: application/json tells the browser (and any code reading the response) that the body is JSON, not plain text or HTML.

  • JSON.stringify(data) converts the JS object into a JSON-formatted string β€” res.end() can only send strings or buffers, not raw objects.

πŸ’» Terminal output:

JSON Server running at <http://localhost:3000>

🌐 Browser output β€” visiting http://localhost:3000 shows the raw JSON:

{"name":"Varsha","course":"Node.js","mood":"Awesome"}

πŸ’‘ Make It Pretty

Browsers show JSON as one unformatted line by default. A JSON formatter extension displays it with indentation and syntax highlighting instead.

πŸ”§ Recommended extensions:

  • 🟒 Chrome β€” JSON Formatter by Callum Locke

  • 🟣 Firefox β€” JSON Lite

  • 🟠 Edge β€” JSON Viewer

With one installed, the same response renders like this instead:

{
  "name": "Varsha",
  "course": "Node.js",
  "mood": "Awesome"
}

✨ Quick Reference

  • πŸ“ Plain text β†’ Content-Type: text/plain

  • πŸ“„ HTML β†’ Content-Type: text/html

  • 🧾 JSON β†’ Content-Type: application/json

res.setHeader('Content-Type', 'text/html');
res.end('<h1>Hello from HTML!</h1><p>This is a web page</p>');