Node.js learning series (2) - create an application

Node.jsThe application consists of three parts:

(1) requireInstructions:

Node.jsIn , use requirethe command to load and import modules. The imported modules can be built-in modules, third-party modules or custom modules.

Grammar format:

const module = require('module-name');

module-nameIt can be a file path (relative or absolute path), or a module name. If it is a module name, the module Node.jswill be automatically searched from node_modulesthe directory .

requireThe command returns the exported object of the loaded module, through which the properties and methods defined in the module can be accessed. If there are multiple exported objects in the module, they can be obtained by destructuring assignment.

var http = require("http");

As shown above, use requirethe directive to load httpthe module and HTTPassign the to the variable http.

(2) Create a server:

The server can listen to the client's request, similar Apache 、Nginxto HTTPthe server.

http.createServer(function (request, response) {
    
    
}).listen(6060 );

As shown above, use http.createServer()the method to create the server, createServerpass an anonymous function to the function, the function receives and responds to data through request, responsethe parameter , and uses listenthe method to bind 6060the port .

(3) Receiving requests and responding to requests:

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

http.createServer(function (request, response) {
    
    
}).listen(6060 );

When the callback fires, two parameters are passed in: requestand response. They are objects that can use their methods to handle the details of HTTPthe request and respond to the request (for example: send something back to the requesting browser).

Now, create a new file D:\demo\nodeunder server.jsto complete a working HTTPserver , the code is as follows:

// 请求(require)Node.js 自带的 http 模块,并且把它赋值给 http 变量
var http = require('http');
const hostname = '127.0.0.1';
const port = 6060;
// 调用 http 模块提供的函数: createServer 。这个函数会返回一个对象,这个对象有一个叫做 listen 的方法,这个方法有一个数值参数, 指定这个 HTTP 服务器监听的端口号
http.createServer(function (request, response) {
    
    
	console.log("Request received.");
    // 发送 HTTP 头部 
    // HTTP 状态值: 200 : OK
    // 内容类型: text/plain
    // 当收到请求时,使用 response.writeHead() 函数发送一个HTTP状态200和HTTP头的内容类型(content-type)
    response.writeHead(200, {
    
    'Content-Type': 'text/plain'});
    // 使用 response.write() 函数在HTTP相应主体中发送文本“response message:"
    response.write("response message:");
    // 调用 response.end() 发送响应数据 "Hello World" 完成响应
    response.end('Hello World!\n');
}).listen(port);

// 终端打印如下信息
console.log(`Server running at http://${
      
      hostname}:${
      
      port}/`);

Run the code with nodethe command :
insert image description here

Open the browser and visit http://localhost:6060/, you can see the page effect as follows:
insert image description here

(Note that when the server accesses the web page, the server may output "Request received." twice. This is because most servers will try to read http://localhost:6060/when http://localhost:6060/favicon.ico)

Guess you like

Origin blog.csdn.net/HH18700418030/article/details/130618696