Table of Contents
1. What is http
Home Web Front-end JS Tutorial 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

Jan 05, 2023 pm 08:31 PM
nodejs​ node http module

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
Copy after login

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();
Copy after login

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) => { 
// 永远相信美好的事情即将发生! 
});
Copy after login

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("<h1>欢迎使用node.js搭建服务</h1>"); 
});
// 绑定端口号
server.listen(8888);

// 控制台打印地址,方便快速调试
console.log('您的http服务启动在  http://127.0.0.1:8888/');
Copy after login

代码运行演示:

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);
Copy after login

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

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

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

当然

还不够好

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

还可以更好!

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

var http = require('http')

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

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to delete node in nvm How to delete node in nvm Dec 29, 2022 am 10:07 AM

How to delete node with nvm: 1. Download "nvm-setup.zip" and install it on the C drive; 2. Configure environment variables and check the version number through the "nvm -v" command; 3. Use the "nvm install" command Install node; 4. Delete the installed node through the "nvm uninstall" command.

How to use express to handle file upload in node project How to use express to handle file upload in node project Mar 28, 2023 pm 07:28 PM

How to handle file upload? The following article will introduce to you how to use express to handle file uploads in the node project. I hope it will be helpful to you!

An in-depth analysis of Node's process management tool 'pm2” An in-depth analysis of Node's process management tool 'pm2” Apr 03, 2023 pm 06:02 PM

This article will share with you Node's process management tool "pm2", and talk about why pm2 is needed, how to install and use pm2, I hope it will be helpful to everyone!

Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Mar 05, 2025 pm 05:57 PM

Detailed explanation and installation guide for PiNetwork nodes This article will introduce the PiNetwork ecosystem in detail - Pi nodes, a key role in the PiNetwork ecosystem, and provide complete steps for installation and configuration. After the launch of the PiNetwork blockchain test network, Pi nodes have become an important part of many pioneers actively participating in the testing, preparing for the upcoming main network release. If you don’t know PiNetwork yet, please refer to what is Picoin? What is the price for listing? Pi usage, mining and security analysis. What is PiNetwork? The PiNetwork project started in 2019 and owns its exclusive cryptocurrency Pi Coin. The project aims to create a one that everyone can participate

What to do if npm node gyp fails What to do if npm node gyp fails Dec 29, 2022 pm 02:42 PM

npm node gyp fails because "node-gyp.js" does not match the version of "Node.js". The solution is: 1. Clear the node cache through "npm cache clean -f"; 2. Through "npm install -g n" Install the n module; 3. Install the "node v12.21.0" version through the "n v12.21.0" command.

Let's talk about how to use pkg to package Node.js projects into executable files. Let's talk about how to use pkg to package Node.js projects into executable files. Dec 02, 2022 pm 09:06 PM

How to package nodejs executable file with pkg? The following article will introduce to you how to use pkg to package a Node project into an executable file. I hope it will be helpful to you!

Token-based authentication with Angular and Node Token-based authentication with Angular and Node Sep 01, 2023 pm 02:01 PM

Authentication is one of the most important parts of any web application. This tutorial discusses token-based authentication systems and how they differ from traditional login systems. By the end of this tutorial, you will see a fully working demo written in Angular and Node.js. Traditional Authentication Systems Before moving on to token-based authentication systems, let’s take a look at traditional authentication systems. The user provides their username and password in the login form and clicks Login. After making the request, authenticate the user on the backend by querying the database. If the request is valid, a session is created using the user information obtained from the database, and the session information is returned in the response header so that the session ID is stored in the browser. Provides access to applications subject to

A brief analysis of how node implements ocr A brief analysis of how node implements ocr Oct 31, 2022 pm 07:09 PM

How to implement OCR (optical character recognition)? The following article will introduce to you how to use node to implement OCR. I hope it will be helpful to you!

See all articles