nodejs: http:send HTML to the Browser

Node.js: Sending HTML to the Browser

If you're building a web application using Node.js, chances are that you'll need to send HTML content to the browser at some point. In this tutorial, we'll explore how to use Node.js to send HTML content to the browser.

Using the http module

The http module in Node.js provides an easy way to create a web server that can respond to HTTP requests. Here's an example of how to use the http module to send HTML content to the browser:


const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write('<div>Hello, World!</div>');
  res.end();
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});

In this example, we create an HTTP server using the createServer() method of the http module. When a request is received, the server responds with a status code of 200 and a content type of 'text/html'. We then write some HTML content using the res.write() method and end the response using the res.end() method.

Using a template engine

While writing HTML content directly in your Node.js code can work for simple applications, it can quickly become unwieldy for more complex applications. A better approach is to use a template engine, which allows you to separate your HTML code from your Node.js code.

There are many template engines available for Node.js, including Handlebars, EJS, and Pug. Here's an example of how to use Handlebars to render HTML content:


const http = require('http');
const handlebars = require('handlebars');

const server = http.createServer((req, res) => {
  res.writeHead(200, {'Content-Type': 'text/html'});
  
  const template = handlebars.compile('<div>Hello, {{name}}!</div>');
  const data = { name: 'Raju' };
  const html = template(data);
  
  res.write(html);
  res.end();
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});

In this example, we use Handlebars to compile a template containing the HTML we want to render. We then pass an object containing any dynamic data we want to include in the HTML to the template, and use handlebars to render the compiled HTML with the dynamic data.

Conclusion

Node.js provides a powerful platform for building web applications. By using the http module or a template engine, you can easily send HTML content to the browser and create dynamic web pages.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe