Detailed explanation of the steps to create a web server with node.js

Detailed explanation of the steps to create a web server with node.js

Preface

It is very simple to create a server in node.js. You only need to use the http module and related APIs provided by node.js to create a small but complete web server. Compared with the process of building a web server in Java/Python/Ruby, it is much simpler.

http model

To create a web server based on Node.js, you must use the http module provided by Node.js. The http interface in Node.js is designed to support many features of the protocol that have traditionally been difficult to use. In particular, large, possibly block-encoded messages, the interface never buffers entire requests or responses, and users are able to stream data.

In order to support all possible http applications, the http APIs of node.js are very low-level, which means that all the complex underlying problems are solved by node.js and encapsulated into modules and related APIs for us to use. You only need to follow the concise syntax of node.js to get started.

Creating a Server

First, you need to import the http module, and then implement some functions through the relevant API. The following is a small but fully functional node web server.

Before creating a server, it is worthwhile to go through these two APIs, or you can come back and look at them again.

(1) Returns a newly created http.Server instance

http.createServer([options][, requestListener])
  • options:<Object>
  • requestListener: <Function>
  • Returns: <http.Server>

(2) Start the HTTP server to listen for connections

server.listen(port,callback)
  • port:<Number>
  • Port number callback: <Function> callback function
  • Returns: None

(3) Printing a string on the screen (using chunks simply)

response.write(chunk[, encoding][, callback])
  • chunk:<String> | <Buffer>
  • encoding:<String> Default value: 'utf8'.
  • callback:<Function> callback
  • Returns: <boolean>

hello.js

// Import core module var http = require('http')

// Create a server (the API returns an instance)
var server = http.createServer()

// Bind port number (3000)
server.listen(3000, () => {
  console.log(`Server started successfully, waiting for client request...`)
})

// Listen for requests from clients server.on('request', (request, response) => {
  
  //Client request path console.log(`Client request path is: ${request.url}`)

  // Respond to the client switch(request.url){
    
    case '/': {//Browser default behavior response.write(`/`)
      break;
    }

    case '/index': {//Homepage response.write(`/index`)
      break;
    }

    case '/loging': {//Login page response.write(`/loging`)
      break;
    }
    
  }

  // Response completed response.end()
  
})

We have finished writing the hello.js web server, now we start the server:

1. Open the cmd terminal and locate the hello.js file directory (IDE built-in terminal is also OK)

insert image description here

2. Start hello.js

// Start the command node hello.js 

insert image description here

If the keyword [Server started successfully...] is displayed, it means the startup is successful, and then open the browser to prepare for testing.

3. Enter the local IP address, like this URL, and the port is the port configured for you, the default is 8000

insert image description here

insert image description here

Test Request

insert image description here

Note that even if you don't write "/", the browser will add it by default.

insert image description here

insert image description here

This concludes this article on the detailed steps of using node.js to create a web server. For more information about using node.js to create a web server, please search for previous articles on 123WORDPRESS.COM or continue browsing the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • How to package Node.js web applications into Docker containers
  • Node.js uses the net module to simulate websocket handshake for data transmission operation example
  • How to Convert SVG Images to PNG, JPEG, TIFF, WEBP and HEIF Formats in Node.js
  • Complete steps to implement web remote desktop with no-vnc and node.js
  • Example of how to build a websocket server with the node.js ws module
  • ws module in node.js creates server and client, webpage WebSocket client
  • How to build a web server using Node.js native API
  • Detailed explanation of how to create a web application using the node.js development framework express
  • Steps to create a WEBSERVER using NODE.JS

<<:  Example code of the spread operator and its application in JavaScript

>>:  About the usage and precautions of promise in javascript (recommended)

Recommend

MySQL 5.7.18 installation and configuration method graphic tutorial (CentOS7)

How to install MySQL 5.7.18 on Linux 1. Download ...

Use of environment variables in Docker and solutions to common problems

Preface Docker can configure environment variable...

InnoDB engine redo file maintenance method

If you want to adjust the size and number of Inno...

Solve the problem of installing Theano on Ubuntu 19

Solution: Directly in the directory where you dow...

A detailed introduction to for/of, for/in in JavaScript

Table of contents In JavaScript , there are sever...

Detailed tutorial on installing Docker and nvidia-docker on Ubuntu 16.04

Table of contents Docker Installation Nvidia-dock...

Vue.js uses Element-ui to implement the navigation menu

This article shares the specific code for impleme...

Docker5 full-featured harbor warehouse construction process

Harbor is an enterprise-level registry server for...

mysql command line script execution example

This article uses an example to illustrate the ex...

Practical method of deleting a row in a MySql table

First, you need to determine which fields or fiel...

Using JS to implement a small game of aircraft war

This article example shares the specific code of ...

Implementation of proxy_pass in nginx reverse proxy

The format is simple: proxy_pass URL; The URL inc...

MySQL 5.7.18 MSI Installation Graphics Tutorial

This article shares the MySQL 5.7.18 MSI installa...