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!
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.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 consoleipconfig
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.
For example, MySQL's 3306, TomCat's 8080
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();
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("<h1 id="欢迎使用node-js搭建服务">欢迎使用node.js搭建服务</h1>"); }); // 绑定端口号 server.listen(8888); // 控制台打印地址,方便快速调试 console.log('您的http服务启动在 http://127.0.0.1:8888/');
Code running demonstration:
上述代码演示十分细节,但是实际开发起来,不建议这样一步步写,过于繁琐了
接下来跟着作者,让我们继续优化一下代码,让代码更加牛逼且简洁
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);
当然
这
还不够好
还可以更好!
直接一个createServer()解决一切:
var http = require('http') // 创建服务器 http.createServer( (req, res) =>{ // 永远相信美好的事情即将发送 }).listen(8888);
看到这里,恭喜你已经入门了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!

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment