Table of Contents
1. What is http
欢迎使用node.js搭建服务
Home Web Front-end JS Tutorial Let's talk about the http module in Node.js

Let's talk about the http module in Node.js

Aug 12, 2022 pm 08:22 PM
nodejs node http module

This article will let you know about the http module in Node, and talk about how to use the http module to create a server. I hope it will be helpful to everyone!

Let's talk about the http module in Node.js

1. What is http

explained in Baidu Encyclopedia:

Hyper Text Transfer Protocol (Hyper Text Transfer Protocol (HTTP) is a simple request-response protocol that 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 protocol

Today 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:

The 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.

Lets talk about the http module in Node.js

1.2. IP address and port number

In 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

You 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.

Lets talk about the http module in Node.jsFor example, MySQL's 3306, TomCat's 8080

2. Use the http module to create a server

Node.jsLets talk about the http module in 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.

2.1, thick accumulation (detailed introduction, detailed introduction of the object methods used, 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 first Create a service object. 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 id="欢迎使用node-js搭建服务">欢迎使用node.js搭建服务</h1>"); 
});
// 绑定端口号
server.listen(8888);

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

Code running demonstration:

Lets talk about 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

当然

还不够好

Lets talk about the http module in Node.js

还可以更好!

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

var http = require('http')

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

Lets talk about the http module in Node.js

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

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

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

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

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

The above is the detailed content of Let's talk about 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Is nodejs a backend framework? Is nodejs a backend framework? Apr 21, 2024 am 05:09 AM

Node.js can be used as a backend framework as it offers features such as high performance, scalability, cross-platform support, rich ecosystem, and ease of development.

How to connect nodejs to mysql database How to connect nodejs to mysql database Apr 21, 2024 am 06:13 AM

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

What is the difference between npm and npm.cmd files in the nodejs installation directory? What is the difference between npm and npm.cmd files in the nodejs installation directory? Apr 21, 2024 am 05:18 AM

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

What are the global variables in nodejs What are the global variables in nodejs Apr 21, 2024 am 04:54 AM

The following global variables exist in Node.js: Global object: global Core module: process, console, require Runtime environment variables: __dirname, __filename, __line, __column Constants: undefined, null, NaN, Infinity, -Infinity

Is there a big difference between nodejs and java? Is there a big difference between nodejs and java? Apr 21, 2024 am 06:12 AM

The main differences between Node.js and Java are design and features: Event-driven vs. thread-driven: Node.js is event-driven and Java is thread-driven. Single-threaded vs. multi-threaded: Node.js uses a single-threaded event loop, and Java uses a multi-threaded architecture. Runtime environment: Node.js runs on the V8 JavaScript engine, while Java runs on the JVM. Syntax: Node.js uses JavaScript syntax, while Java uses Java syntax. Purpose: Node.js is suitable for I/O-intensive tasks, while Java is suitable for large enterprise applications.

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

Is nodejs a back-end development language? Is nodejs a back-end development language? Apr 21, 2024 am 05:09 AM

Yes, Node.js is a backend development language. It is used for back-end development, including handling server-side business logic, managing database connections, and providing APIs.

How to deploy nodejs project to server How to deploy nodejs project to server Apr 21, 2024 am 04:40 AM

Server deployment steps for a Node.js project: Prepare the deployment environment: obtain server access, install Node.js, set up a Git repository. Build the application: Use npm run build to generate deployable code and dependencies. Upload code to the server: via Git or File Transfer Protocol. Install dependencies: SSH into the server and use npm install to install application dependencies. Start the application: Use a command such as node index.js to start the application, or use a process manager such as pm2. Configure a reverse proxy (optional): Use a reverse proxy such as Nginx or Apache to route traffic to your application

See all articles