May 10, 2021 Node.js
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:
Introduction of the required module: We can use the require instruction to load .js module.
Create a server: The server can listen to requests from clients, similar to HTTP servers such as Apache, Nginx, and so on.
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.
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");
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/
Next, open your browser to http://127.0.0.1:8888/ and you'll see a web page that says "Hello World."
Analysis of .js's HTTP servers:
Next, let's show you the example operation with the Gif diagram: