Home  >  Article  >  Web Front-end  >  This article will take you to understand the http module in Node.js

This article will take you to understand the http module in Node.js

青灯夜游
青灯夜游forward
2023-01-05 20:31:052095browse

This article will introduce you to the Node.js http module and introduce how to use the http module to create a server. I hope it will be helpful to you!

This article will take you to understand the http module in Node.js

1. What is http

explained in Baidu Encyclopedia:

Hypertext transmission The protocol (Hyper Text Transfer Protocol, HTTP) is a simple request-response protocol, which usually runs on top of TCP. It specifies what kind of messages the client may send to the server and what kind of response it gets. The headers of request and response messages are given in the form ASCII; while the [9] message content has a format similar to MIME. This simple model was instrumental in the early success of the Web because it made development and deployment very straightforward. If you have learned the basics of JavaSE, you should be very familiar with network programming

Of course, it’s okay if you haven’t. Let me tell you what a conscientious author tells you:

1.1. Network communication protocolToday in 2022, computer networks have become a necessity for people’s daily lives, whether it is email or instant messaging with friends , short video entertainment... It can be said that we can connect multiple computers through computer networks.

Computer networks connect multiple computer devices under a network through transmission media, communication facilities, and network communication protocols, realizing resource sharing and data transmission.

But when computers on the same network connect and communicate, they must abide by certain rules. In computer networks, these rules for connection and communication are called network communication protocols:

This article will take you to understand the http module in Node.jsThe http protocol we are talking about here is implemented based on tcp. A common http application scenario is that you enter a string of addresses in the browser and then return a web page.

1.2. IP address and port numberIn order to enable computers in the network to communicate, each computer must also be assigned a Identification number, through which the computer that receives the data or the computer that sends the data is designated.

Check the IP address of your computer on the LAN

Press WIN R on the Windows computer and enter cmd to quickly enter the console

ipconfig

This article will take you to understand the http module in Node.jsYou can connect to the specified computer through the IP address, but if you want to access one of your applications on the target computer, you also need to specify the port number.

For example, MySQL's 3306, TomCat's 8080

2. Use the http module to create a server

This article will take you to understand the http module in Node.js

Node.js

provides the http module. The http module is mainly used to build HTTP server and client. To use the HTTP server or client function, the http module must be called. [Recommended related tutorials: nodejs video tutorial, Programming teaching]

2.1, thick accumulation (detailed explanation, detailed introduction to the objects used Method, the entire http service construction process)Process introduction:

    First use the createServer() method to register the server object,
  • Then use this server object to call the on() method to listen for and process events,
  • Call the listen() method to bind the port number
  • Start with a taste:

Any network service application must always create a service object first. In nodeJS we can use the createServer method to achieve this.

// 首先导入http模块
const http = require('http'); 
// 创建http服务对象
const server = http.createServer();

The Server object returned by the createServer constructor is an event emitter. Here, the created server object is used to use its own on() method. Perform event monitoring and processing on it. In this way, whenever an http request is sent, we can process it.

// 首先导入http模块
const http = require('http'); 
// 创建http服务对象
const server = http.createServer();
// 绑定事件监听
server.on('request', (request, response) => { 
// 永远相信美好的事情即将发生! 
});

We introduced (IP address port) before. When our computer is connected to the Internet, the router will automatically DHCP assign the IP address to us, but if we want to access the specified program on the computer, we must also have a port number. .

In order to access the specified program on the computer, we also need to use the listen() method. You only need to use server.listen() to pass the port number as a parameter into the listen method as the listening port.

// 首先导入http模块
const http = require('http'); 
// 创建http服务对象
const server = http.createServer();
// 绑定事件监听
server.on('request', (req, res) => {  
// 此函数内容只是小小调用一下res参数让程序更加易懂的跑起来
    // 编写响应头(不写浏览器不识别)
    res.writeHead(200,{'Content-Type':'text/html;charset=UTF8'});
    // 发送响应数据
    res.end("

欢迎使用node.js搭建服务

");  }); // 绑定端口号 server.listen(8888); // 控制台打印地址,方便快速调试 console.log('您的http服务启动在  http://127.0.0.1:8888/');

代码运行演示:

This article will take you to understand the http module in Node.js

上述代码演示十分细节,但是实际开发起来,不建议这样一步步写,过于繁琐了

接下来跟着作者,让我们继续优化一下代码,让代码更加牛逼且简洁

2.2、薄发(极简才是王道,优雅!太优雅了!!!)

一步一步注册对象,调各种方法的流程太过繁琐,这里我们用小而美的做法,一步踏天,实现一个http接口:

const http = require('http'); 
const server = http.createServer(function(req,res){ 
  // 永远相信美好的事情即将发生
}).listen(8080);

每当有 HTTP 请求到达服务器时,createServer 中传入的函数就被自动执行。所以这个函数也被称为是请求处理函数。我们可以直接在里面传入事件监听的回调函数,然后后面点上listen()方法,直接绑定端口号。

但是这样还不够好,是的,还可以更好,把上面回调函数用箭头函数修饰一下,更加美观。

const http = require('http'); 
const server = http.createServer((req,res) => { 
  // 永远相信美好的事情即将发生
}).listen(8080);

当然

还不够好

This article will take you to understand the http module in Node.js

还可以更好!

直接一个createServer()解决一切:

var http = require('http')

// 创建服务器
http.createServer( (req, res) =>{  
    // 永远相信美好的事情即将发送
 }).listen(8888);

This article will take you to understand the http module in Node.js

看到这里,恭喜你已经入门了nodeJS的http模块 此时此刻的你 已经掌握了如下技能

  • 实例化一个 HTTP 服务,绑定一个处理请求的函数,并对某个特定端口进行监听。

请继续关注作者,接下来 我们将学习

  • request 中获取请求头,访问路径,方法以及消息体。
  • response 象发送响应头,HTTP 状态码以及消息体。
  • server.on()的相关参数 进行错误、超时、连接·····等等情况的处理

更多node相关知识,请访问:nodejs 教程

The above is the detailed content of This article will take you to understand the http module in Node.js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete