Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Node .js create the first app


May 10, 2021 Node.js


Table of contents


Node .js create the first app

If we use PHP to write back-end code, we need apache or Nginx's HTTP server with mod_php5 module and php-cgi.

From this perspective, the entire "receive HTTP request and provide Web page" requirement does not need PHP to handle at all.

But for .js, the concept is completely different. W hen using .js, we implemented not only one application, but also the entire HTTP server. In fact, our Web applications and corresponding Web servers are basically the same.

Before we created .js the first "Hello, World!" Before we apply, let's look at .js Node's application is made up of:

  1. Introduction of the required module: We can use the require instruction to load .js module.

  2. Create a server: The server can listen to requests from clients, similar to HTTP servers such as Apache, Nginx, and so on.

  3. Receive requests and response requests: Servers are easy to create, clients can use browsers or terminals to send HTTP requests, and servers receive requests and return response data.


Create a Node .js app

Step 1, the introduction of required module

We use the require instruction to load the http module and assign the instantiated HTTP to the variable http, as follows:

var http = require("http");

Step 1, Create a server

Next, we use the http.createServer() method to create the server and use the listn method to bind port 8888. Functions receive and respond to data through request, response parameters.

Here's an example of creating a file called server at the root .js project and writing the following code:

var http = require('http');

http.createServer(function (request, response) {

	// 发送 HTTP 头部 
	// HTTP 状态值: 200 : OK
	// 内容类型: text/plain
	response.writeHead(200, {'Content-Type': 'text/plain'});

	// 发送响应数据 "Hello World"
	response.end('Hello World\n');
}).listen(8888);

// 终端打印如下信息
console.log('Server running at http://127.0.0.1:8888/');

The above code we have completed a working HTTP server.

Use the node command to execute the above code:

node server.js
Server running at http://127.0.0.1:8888/

Node .js create the first app

Next, open your browser to http://127.0.0.1:8888/ and you'll see a web page that says "Hello World."

Node .js create the first app

Analysis of .js's HTTP servers:

  • The first line requests (require) Node .js http module that is included and assigned to the http variable.
  • Next we call the function provided by the http module: createServer. This function returns an object that has a method called listen, which has a numeric parameter that specifies the port number that the HTTP server listens to.

Gif instance demo

Next, let's show you the example operation with the Gif diagram:

Node .js create the first app