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

How to configure MySQL master-slave synchronization in Ubuntu 16.04

Preparation 1. The master and slave database vers...

Summarize the common properties of BigIn functions in JavaScript

Table of contents 1. Overview 2. Attributes 1. Ma...

Parsing the commonly used v-instructions in vue.js

Table of contents Explanation of v-text on if for...

Practical TypeScript tips you may not know

Table of contents Preface Function Overloading Ma...

Docker deployment RabbitMQ container implementation process analysis

1. Pull the image First, execute the following co...

How to build a private Docker repository using Harbor

Table of contents 1. Open source warehouse manage...

jQuery canvas generates a poster with a QR code

This article shares the specific code for using j...

Ubuntu 20.04 connects to wifi (2 methods)

I recently installed Ubuntu 20.04 and found that ...

Two ways to achieve horizontal arrangement of ul and li using CSS

Because li is a block-level element and occupies ...

Vite2.0 Pitfalls

Table of contents Vite project build optimization...

Detailed explanation of mysql exists and not exists examples

Detailed explanation of mysql exists and not exis...