Node.js Create your first application


If we use PHP to write back-end code, we need an Apache or Nginx HTTP server, coupled with the mod_php5 module and php-cgi.

From this perspective, the entire need of "receiving HTTP requests and serving Web pages" does not require PHP to handle it at all.

But for Node.js, the concept is completely different. When using Node.js, we are not only implementing an application, but also an entire HTTP server. In fact, our web application and corresponding web server are basically the same.

Before we create the first "Hello, World!" application in Node.js, let us first understand what parts the Node.js application consists of:

  1. Introducing the required module: We can use the require directive to load the Node.js module.

  2. Create server: The server can monitor client requests, similar to HTTP servers such as Apache and Nginx.

  3. Receiving requests and responding to requests The server is easy to create. The client can use a browser or terminal to send HTTP requests, and the server returns response data after receiving the request.


Create Node.js application

Step 1. Introduce the required module

We use the require command to load Enter the http module and assign the instantiated HTTP value to the variable http. The example is as follows:

var http = require("http");

Step 1. Create the server

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

The example is as follows. Create a file called server.js in the root directory of your project and write 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/');

With the above code, we have completed a working HTTP server.

Use the node command to execute the above code:

node server.jsServer running at http://127.0.0.1:8888/

cmdrun

##Next, open the browser and visit http://127.0.0.1 :8888/, you will see a message that says "Hello World" web page.

nodejs-helloworld

Analysis of Node.js HTTP server:

  • The first line requests Node. The http module that comes with js and assign it to http variable.

  • Next we call the function provided by the http module: createServer. This function will return An object. This object has a method called listen. This method has a numeric parameter. Specify the port number this HTTP server listens on.


Gif Example Demonstration

Next, we will demonstrate the example operation through Gif pictures: