1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Your first Node.js server

Discussion in 'JavaScript' started by rinaricci, Jul 17, 2019.

  1. #1
    In this article, I want to tell you how you can start a simple Node.js HTTP server and begin processing requests.

    The HTTP module for your Node.js server
    When you start creating HTTP-based applications in Node.js, the built-in HTTP/HTTPS modules are the ones you will interact with.

    Now, let’s build your first Node.js HTTP server! We will need to require the HTTP module and bind our server to the port 3000.

    // content of index.js 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}`) })

    Now, you need to execute the following :

    $ node index.js

    Here are several important issues you should take into account:
    • requestHandler: this function will be executed every time a request reaches the server. In case you go to localhost:3000 in your browser, you will see two log messages appear: one for / and one for favicon.ico
    • if (err): error handling - in case the port is already used, or for any other reason our server cannot start, we get notifications here

    Actually, the HTTP module is rather a low-level entity: creating a compound web solution using the mentioned above code snippet is quite time-consuming. On this account, I usually choose a framework to work with our projects. Naturally, there are tons of variants to choose from. However, the following list of options seems to be the most popular one:

    • express

    • hapi

    • koa

    • restify
    In the following sections, I am going to utilize Express. The reason is that there are tons of NPM modules for Express.

    Express
    It stands for the fast, flexible, minimalistic web framework for Node.js - http:// expressjs.com/

    Initially, you need to add Express to your project using NPM:

    $ npm install express --save

    When you have installed Express, let’s discuss how you can build a similar application as you did 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}`) })

    The biggest difference you can notice here is that Express provides you with a router by default. You do not need to manually parse the URL to decide what to do. Instead, you define the application routing using app.get, app.post, app.put and other request methods, and they are already translated into the corresponding HTTP requests.

    Middleware pattern refers to one of the most powerful concepts implemented by Express.

    Middlewares
    Actually, you can treat middlewares as Unix pipelines, but used for HTTP requests.


    [​IMG]


    In the mentioned diagram, you can behold the way a request goes through an Express application. It travels to three middlewares. Each can modify it, then based on the business logic either the third middleware can send back a response or it can be a route handler.

    Concerning a real application development, you can make it as follows:

    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)

    There are several important points we should discuss here:
    • app.use: this refers to the way you can define middlewares. This method takes a function with three parameters. The first one is the request, the second is the response and the last one is the next callback. Calling next gives you an opportunity to signal Express that it can move to the next next intermediate handler.

    • The first intermediate handler just logs the headers and immediately calls the next middleware.

    • The second handler adds an additional property to the request. It is considered to be one of the most powerful middleware pattern features. Your intermediate handlers can add extra data to the request object. Those middlewares located beneath can read and change it.
    Error processing
    Just like in all frameworks, the correct and proper error processing has a fundamental importance. Considering Express, you need to create a special event listener, 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) => {

    // log the error, for now just console.log console.log(err) response.status(500).send(‘Something broke!’)

    })

    There are several important points that should be covered here:
    • The error handler should be the last function added with the help of app.use.

    • The error handler takes a next callback. So, it can be used to chain multiple error handlers.
    HTML Rendering
    Previously, we have discussed how to send JSON responses. Now, it is time to master how to render HTML in easy and convenient way. For this purpose, I am going to utilize the handlebars package with the express-handlebars wrapper.

    Initially, you need to create the following directory structure:

    ├── index.js └── views

    ├── home.hbs └── layouts

    └── main.hbs

    When you have created the following structure, you need to fill index.js file with the following data:

    // index.js

    const path = require(‘path’)

    const express = require(‘express’)

    const exphbs = require(‘express-handlebars’)

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

    Thus, the above mentioned code block installs the handlebars engine and stores the layouts catalogue to views/layouts. Actually, it is the directory where your layouts will be placed.

    When you have configured this setup, you can insert your initial HTML into the main.hbs. In order to keep things simple and comprehensive, let’s go ahead with the following one:

    <html> <head>

    <title>Express handlebars</title> </head>

    <body> {{{body}}}

    </body> </html>

    Here, you can behold the {{{body}}} placeholder. It is the place where your content will be stores. Now, let’s create the home.hbs!

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

    The last thing we need to do to run the application is to add a route handler to our Express application:

    app.get(‘/’, (request, response) => { response.render(‘home’, {

    name: ‘John’ })

    })

    Actually, the render method takes two parameters:

    • The first param is the template name

    • The second param is the data to be rendered.

    As soon as you send the request to that address, you should receive something like this:

    <html> <head>

    <title>Express handlebars</title> </head>

    <body>

    <h2>Hello John<h2>

    </body> </html>

    Honestly, it is just a sliver of the full scope. If you want to learn how to add more layouts (even partials), you can read the official express-handlebars documentation.

    Debugging Express
    Under certain circumstances, you may want to see what happens with Express when your application is running. In order to see it, you can pass the following environment variable to Express:

    DEBUG=express*.

    Finally, you need to start your Node.js HTTP server with the following command:

    $ DEBUG=express* node index.js

    Conclusion
    In this article, I have shown the way you can start your first Node.js HTTP server from scratch. Actually, I recommend using Express at the beginning. When you obtain a solid experience, you should then feel free to experiment with different frameworks.


    In the next chapter, I will tell you how to retrieve data from databases.

    Author: Denis Zarytskyi, developer at https://writeabout.tech
     
    rinaricci, Jul 17, 2019 IP