In this blog of Node.js HTTP, we will discuss Node.js and deliver software products using it. Also, we will discuss how you can fire up a simple Node.js HTTP server and start serving requests.

Node.js HTTP

Also Read: Node js on hosting: Best Hosting Platforms for 2021

Node.js HTTP server module

Node.js HTTP

You will interact with the built-in http/https modules when you start to build HTTP-based applications in Node.js. Now we will create the first Node.js HTTP server. And for that, we require the http module and bind your server to the port 3000 to listen on.

<em>// content of index.js</em>
const http = require('http')
const port = 3000

const requestHandler = (request, response) => {
  console.log(request.url)
  response.end('Hello Node.js Server!')
}

const server = http.createServer(requestHandler)

server.listen(port, (err) => {
  if (err) {
    return console.log('something bad happened', err)
  }

  console.log(`server is listening on ${port}`)
})

Let’s start with the following:

$ node index.js

You need to pay attention to a few things here:

  • requestHandler: You can invoke this function every time a request hits the server. When you visit  localhost:3000 from your browser, two log messages will appear on your screen . Firstly, for / and secondly for favicon.ico.
  • if (err): error handling – In case of the port already taken or other reasons, the server is unable to start then you will be notified here.

The http module is low-level that creates a complex web application and using the snippet given above can consume your time very much. Because of this people usually pick a framework to work with for our projects. You have various options to pick up from such as the following:

  • Koa
  • express
  • hapi
  • restify

We are going to use Express from now on for this blog as you will find the most modules on NPM for Express.

Express

The web framework for Node.js that is fast, unopinionated, and minimalist is  http://expressjs.com/. You can add Express to your project on NPM by installation:

$ npm install express --save

After the installation of Express, we will create a similar application as before:

const express = require('express')
const app = express()
const port = 3000

app.get('/', (request, response) => {
  response.send('Hello from Express!')
})

app.listen(port, (err) => {
  if (err) {
    return console.log('something bad happened', err)
  }

  console.log(`server is listening on ${port}`)

There is a big difference which you should notice that Express by default gives you a router. You don’t require to check manually for the URL to decide what to do. However, you can define the application’s routing with app.getapp.postapp.put, etc. instead. These are translated to the corresponding HTTP verbs. Express implements one of the most powerful concepts called the middleware pattern.

Middlewares

You can understand middlewares by thinking of them as Unix pipelines, but for HTTP requests.

https://i.ytimg.com/vi/EprUiOvF3Lo/maxresdefault.jpg

From the diagram, you can understand how a request goes through an Express application. It can travel to three middlewares. Everyone of them can modify it, then on the basis of the business logic either the third middleware sends back a response or it can be a route handler. You can do so in the following way in your practice:

const express = require('express')
const app = express()

app.use((request, response, next) => {
  console.log(request.headers)
  next()
})

app.use((request, response, next) => {
  request.chance = Math.random()
  next()
})

app.get('/', (request, response) => {
  response.json({
    chance: request.chance
  })
})

app.listen(3000)

You should note the following things here:

  • app.use: In this way, you can define middlewares. It can take a function with three parameters: firstly, the request, secondly, the response and lastly is the  next callback.
  • The first middleware can just log the headers and call the next one instantly.
  • The second middleware can add an extra property to it. People consider it as one of the most powerful features of the middleware pattern.

Error Handling

It is necessary to get the error handling right in all the frameworks. You need to create a special middleware function in Express for doing so  – a middleware with four parameters:

const express = require('express')
const app = express()

app.get('/', (request, response) => {
  throw new Error('oops')
})

app.use((err, request, response, next) => {
  <em>// log the error, for now just console.log</em>
  console.log(err)
  response.status(500).send('Something broke!')
})

You should note the following things here:

  • The error handler function must be the last function to add with app.use.
  • The error handler has a next callback that you can use to chain multiple error handlers.

Rendering HTML

https://i.ytimg.com/vi/EprUiOvF3Lo/maxresdefault.jpg

In this blog, we have understood how to send JSON responses until now. Now we will learn rendering HTML the easy way. We are going to do so by using the handlebars package with the express-handlebars wrapper.

Firstly, we should create the following directory structure:

├── index.js
└── views
    ├── home.hbs
    └── layouts
        └── main.hbs

After doing so, populate index.js with the snippet mentioned below:

<em>// index.js</em>
const path = require('path')
const express = require('express')
const exphbs = require('express-handlebars')

const app = express()

app.engine('.hbs', exphbs({
  defaultLayout: 'main',
  extname: '.hbs',
  layoutsDir: path.join(__dirname, 'views/layouts')
}))
app.set('view engine', '.hbs')
app.set('views', path.join(__dirname, 'views'))

The above code is initializing the handlebars engine and setting the layouts directory to views/layouts. All your layouts will be stored in this directory. After doing this setup, you will be able to put your initial html into the main.hbs. We will go with the following for keeping things simple:

<html>
  <head>
    <title>Express handlebars</title>
  </head>
  <body>
    {{{body}}}
  </body>
</html>

Here you should notice the {{{body}}} placeholder as this is where your content will be placed. Now let’s create the home.hbs!

<h2>Hello {{name}}<h2>

Lastly, you have to add a route handler to our Express application:

app.get('/', (request, response) => {
  response.render('home', {
    name: 'John'
  })
})

The render method has the following two parameters:

  • Firstly, the name of the view,
  • Secondly, the data you want to render.

After calling that endpoint, you will end up with the following:

<html>
  <head>
    <title>Express handlebars</title>
  </head>
  <body>
    <h2>Hello John<h2>
  </body>
</html>

Debugging Express

Sometimes people require to see what happens with Express when the application is running. You can do so by passing the following environment variable to Express: DEBUG=express*. You can start your Node.js HTTP server using:

$ DEBUG=express* node index.js

Conclusion

With the help of this blog, you can set up your first Node.js HTTP server from scratch. We recommend that you start with Express then move on for experimenting. Thank you for reading our blog!

Categorized in:

Tagged in: