search
HomeWeb Front-endJS TutorialTake you to understand the HTTP module in depth

Take you to understand the HTTP module in depth

Jun 09, 2022 pm 07:28 PM
nodejs​node.jsnodehttp module

This article will help you learn about the http module and lay the foundation for writing interfaces. I hope it will be helpful to you!

Take you to understand the HTTP module in depth

1. Web server

What is a web server?

When the application (client) needs a certain resource, it can obtain the resource through an HTTP request to a server; the server that provides the resource is a Web server;

1.1 First experience with the server

Take you to understand the HTTP module in depth

##1.2 Two ways to create a server

    http.createServer will return the server object
  • The bottom layer actually uses the direct new Server object

Take you to understand the HTTP module in depth

1.3 request object

#The request object encapsulates all the information passed by the client to our server

  • The URL of this request, the server needs to process it differently according to different URLs;

  • The request method of this request, such as the parameters passed in GET and POST requests The processing method is different;

  • The headers of this request will also carry some information, such as client information, format for receiving data, supported encoding formats, etc...

General request:

Take you to understand the HTTP module in depth

Take you to understand the HTTP module in depth

##1.3.1 request-url

When the client sends a request, it will request different data, and then different request addresses will be passed in. The server needs to make different responses based on different request addresses.

If the user's request address also carries some additional parameters, how should we parse it?

We can use the url module.

Among them, the url module provides practical tools for URL processing and parsing

Import url const url = require('url')

Assume that our request data is:


Take you to understand the HTTP module in depthThe result of the console parsing the url is:

Take you to understand the HTTP module in depthThe pathname is the final path we need to obtain. Our purpose is to obtain username and password separately in the query.

Import querystring module

const qs = require('querystring');

<pre class="brush:php;toolbar:false">const http = require(&quot;http&quot;)const url = require('url')const qs = require('querystring')// 1. 创建服务器const server = http.createServer((req, res) =&gt; {   // 使用内置模块   const{ pathname,query } = url.parse(req.url)   if(pathname === '/login'){     console.log(query);     console.log(qs.parse(query));     const { username, password } = qs.parse(query)     console.log(username,password);     res.end('请求结束')   }});// 2. 设置端口号并启动服务器server.listen(8888,'0.0.0.0',()=&gt;{   console.log(&quot;服务器启动成功~&quot;);})</pre>

✅Console output result:

  • Take you to understand the HTTP module in depth
1.3.2 request-method

In the Restful specification (design style), we should use different request methods for adding, deleting, modifying and checking data:

GET: Query data;
  • POST: Create new data;
  • PATCH: Update data;
  • DELETE: Delete data
  • We can perform different processing by judging different request methods.

Assume the following is our JSON request data in the body ->How to make our server obtain the username and password?

Take you to understand the HTTP module in depth

Take you to understand the HTTP module in depth##✅Console output


  • Take you to understand the HTTP module in depth
  • 1.3.2 request-headers

##content-type is the type of data carried in this request: Take you to understand the HTTP module in depth

application/json means a json type;

text/plain means a text type;
  • application/xml means an xml type;
  • multipart/form-data Indicates uploading a file;
  • **content-length: **The size and length of the file
keep-alive:

  • http is based on the TCP protocol, but it is usually interrupted immediately after a request and response;
  • In http1.0, if you want to continue to maintain the connection: ①The browser requires Add connection: keep-alive in the request header; ② The server needs to add connection: keey-alive in the response header; ③ When the client makes a request again, the same connection will be used, and the direct party will interrupt the connection;
  • In http1.1, all connections default to connection: keep-alive: ① Different Web servers will have different keep-alive times; ② The default in Node is 5s

**accept-encoding: **Inform the server that the file compression format supported by the client. For example, js files can be encoded using gzip, corresponding to .gz files

**accept: **Inform the server that the client is acceptable File format type;

**user-agent: **Client-related information;

1.4 response object

1.4.1 response-response object

If we want to respond to the client with result data, we can do so in two ways:

  • Write method: This method writes the data directly, but does not close the stream;
  • end method: This method writes the last data, and the stream will be closed after writing;

Note: If we do not call end and close, the client will wait for the result.

1.4.2 response-response code

Http Status Code (Http Status Code) is a numeric code used to represent the Http response status:

  • Http status codes are very many, and different status codes can be returned to the client according to different situations;
  • The common status codes are the following (the status codes will also be used in subsequent projects )
  • http status code collection
1xxInformational (Informational Status Code)Accepted Request Processing2xxSuccess (success status code)The request has been processed normally3xx RedirectionAdditional action required to complete the request4xxClient error Client request error, the server cannot process the request5xxServer ErrorThe server has an error processing the request

##Category Reason Phrase
Common response codes:

##Status codeDescription statusDescription##200OKThe request was successful. Generally used for GET and POST requests400Bad RequestThe client request has a syntax error and the server cannot understand401UnauthorizedThe request requires user authentication403ForbiddenThe server understands the request from the client, but refuses to execute the request 404Not FoundThe server cannot find the resource based on the client's request ( Web page). Through this code, website designers can set up a personalized page for "The resource you requested cannot be found"500Internal Server ErrorServer Internal error, unable to complete the request503Service UnavailableThe server is temporarily unable to process the client's request due to overload or system maintenance. The length of the delay can be included in the server's Retry-After header informationSet status code:

Take you to understand the HTTP module in depth
Take you to understand the HTTP module in depth1.4.3 response-response header

There are two main ways to return header information:

res.setHeader: Write one header information at a time;

    res.writeHead: Write header and status at the same time

  • Take you to understand the HTTP module in depth
    Take you to understand the HTTP module in depthMore For more node-related knowledge, please visit:
  • nodejs tutorial
!

The above is the detailed content of Take you to understand the HTTP module in depth. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

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.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

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.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

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.

See all articles

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

MantisBT

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.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor