1, opening analysis
First of all, everyone should be familiar with the concept of "Http". It is not based on a specific language. It is a general application layer protocol. Different languages have different implementation details, but they remain the same and the ideas are the same.
As a host operating environment, NodeJS uses JavaScript as the host language. It also has its own set of standards for implementation. In this article, we will learn about the "Http module" together. But as a premise,
I hope you can read the API provided by the official website first and have a pre-understanding, which will be much more convenient. The following is an overview of the API of the Http part:
HTTP
http.STATUS_CODES
http.createServer([requestListener])
http.createClient([port], [host])
Class: http.Server
事件 : 'request'
事件: 'connection'
事件: 'close'
Event: 'checkContinue'
事件: 'connect'
Event: 'upgrade'
Event: 'clientError'
server.listen(port, [hostname], [backlog], [callback])
server.listen(path, [callback])
server.listen(handle, [callback])
server.close([callback])
server.maxHeadersCount
server.setTimeout(msecs, callback)
server.timeout
Class: http.ServerResponse
事件: 'close'
response.writeContinue()
response.writeHead(statusCode, [reasonPhrase], [headers])
response.setTimeout(msecs, callback)
response.statusCode
response.setHeader(name, value)
response.headersSent
response.sendDate
response.getHeader(name)
response.removeHeader(name)
response.write(chunk, [encoding])
response.addTrailers(headers)
response.end([data], [encoding])
http.request(options, callback)
http.get(options, callback)
Class: http.Agent
new Agent([options])
agent.maxSockets
agent.maxFreeSockets
agent.sockets
agent.freeSockets
agent.requests
agent.destroy()
agent.getName(options)
http.globalAgent
Class: http.ClientRequest
Event 'response'
Event: 'socket'
事件: 'connect'
Event: 'upgrade'
Event: 'continue'
request.write(chunk, [encoding])
request.end([data], [encoding])
request.abort()
request.setTimeout(timeout, [callback])
request.setNoDelay([noDelay])
request.setSocketKeepAlive([enable], [initialDelay])
http.IncomingMessage
事件: 'close'
message.httpVersion
message.headers
message.rawHeaders
message.trailers
message.rawTrailers
message.setTimeout(msecs, callback)
message.method
message.url
message.statusCode
message.socket
让我们先从一个简单例子开始,创建一个叫server.js的文件,并写入以下代码:
var http = require('http') ;
var server = http.createServer(function(req,res){
res.writeHeader(200,{
'Content-Type' : 'text/plain;charset=utf-8' // Add charset=utf-8
}) ;
res.end("Hello, Big Bear!") ;
}) ;
server.listen(8888) ;
console.log("http server running on port 8888 ...") ;
(node server.js) The following are the results:
2. Detailed analysis examples
Look at this small example in detail:
(Line 1): Introduce the "http" module that comes with NodeJS through "require" and assign it to the http variable.
(2 lines): Call the function provided by the http module: "createServer". This function returns a new web server object.
The parameter "requestListener" is a function that will automatically be added to the listening queue of the "request" event.
When a request comes, Event-Loop will put the Listener callback function into the execution queue, and all the code in the node will be taken out of the execution queue one by one for execution.
These executions are all performed on the working thread (Event Loop itself can be considered to be in an independent thread. We generally do not mention this thread, but call node a single-threaded execution environment),
All callbacks are run on a worker thread.
Let’s take a look at the callback function "requestListener" again, which provides two parameters (request, response),
Fired every time a request is received. Note that each connection may have multiple requests (in a keep-alive connection).
"request" is an instance of http.IncomingMessage. "response" is an instance of http.ServerResponse.
An http request object is a readable stream, and an http response object is a writable stream.
An "IncomingMessage" object is created by http.Server or http.ClientRequest,
And passed as the first parameter to the "request" and "response" events respectively.
It can also be used to access response status, headers and data.
It implements the "Stream" interface and the following additional events, methods and properties. (Refer to API for details).
(3 lines): "writeHeader", use the "response.writeHead()" function to send an Http status 200 and the content-type of the Http header.
Reply the response header to the request. "statusCode" is a three-digit HTTP status code, such as 404. The last parameter, "headers", is the content of the response headers.
Give me an example:
var body = 'hello world' ;
response.writeHead(200, {
‘Content-Length’: body.length,
'Content-Type': 'text/plain'
}) ;
Note: Content-Length is calculated in bytes, not characters.
The reason for the previous example is that the string "Hello World!" only contains single-byte characters.
If the body contains multi-byte encoded characters, you should use Buffer.byteLength() to determine the number of bytes of the string in the case of multi-byte character encoding.
It should be further explained that Node does not check whether the Content-Lenth attribute matches the transmitted body length.
statusCode is a three-digit HTTP status code, for example: "404". What I want to talk about here is "http.STATUS_CODES", which contains the collection and short description of all standard "Http" response status codes.
The following is the source code reference:
var STATUS_CODES = exports.STATUS_CODES = {
100 : 'Continue',
101 : 'Switching Protocols',
102 : 'Processing', // RFC 2518, obsoleted by RFC 4918
200 : 'OK',
201 : 'Created',
202 : 'Accepted',
203 : 'Non-Authoritative Information',
204 : 'No Content',
205 : 'Reset Content',
206 : 'Partial Content',
207 : 'Multi-Status', // RFC 4918
300 : 'Multiple Choices',
301 : 'Moved Permanently',
302 : 'Moved Temporarily',
303 : 'See Other',
304 : 'Not Modified',
305 : 'Use Proxy',
307 : 'Temporary Redirect',
400 : 'Bad Request',
401 : 'Unauthorized',
402 : 'Payment Required',
403 : 'Forbidden',
404 : 'Not Found',
405 : 'Method Not Allowed',
406 : 'Not Acceptable',
407 : 'Proxy Authentication Required',
408 : 'Request Time-out',
409 : 'Conflict',
410 : 'Gone',
411 : 'Length Required',
412 : 'Precondition Failed',
413 : 'Request Entity Too Large',
414 : 'Request-URI Too Large',
415 : 'Unsupported Media Type',
416 : 'Requested Range Not Satisfiable',
417 : 'Expectation Failed',
418 : 'I'm a teapot', // RFC 2324
422 : 'Unprocessable Entity', // RFC 4918
423 : 'Locked', // RFC 4918
424 : 'Failed Dependency', // RFC 4918
425 : 'Unordered Collection', // RFC 4918
426 : 'Upgrade Required', // RFC 2817
500 : 'Internal Server Error',
501 : 'Not Implemented',
502 : 'Bad Gateway',
503 : 'Service Unavailable',
504 : 'Gateway Time-out',
505 : 'HTTP Version not supported',
506 : 'Variant Also Negotiates', // RFC 2295
507 : 'Insufficient Storage', // RFC 4918
509 : 'Bandwidth Limit Exceeded',
510 : 'Not Extended' // RFC 2774
};
节选自,Nodejs源码 ”http.js“ 143行开始。
其实从客户端应答结果也不难看出:
(6行):”response.end“------当所有的响应报头和报文被发送完成时这个方法将信号发送给服务器。服务器会认为这个消息完成了。
每次响应完成之后必须调用该方法。如果指定了参数 “data” ,就相当于先调用 “response.write(data, encoding) ” 之后再调用 “response.end()” 。
(8行):”server.listen(8888)“ ------ 服务器用指定的句柄接受连接,绑定在特定的端口。
以上就是一个比较详细的分析过程,希望有助于加深理解,代码虽然不多,但是重在理解一些细节机制,以便日后高效的开发NodeJS应用。
三,实例
除了可以使用"request"对象访问请求头数据外,还能把"request"对象当作一个只读数据流来访问请求体数据。
这是一个"POST"请求的例子:
http.createServer(function (request, response) {
var body = [];
console.log(request.method) ;
console.log(request.headers) ;
Request.on('data', function (chunk) {
body.push(chunk);
}) ;
Request.on('end', function () {
body = Buffer.concat(body);
console.log(body.toString()) ;
});
}).listen(8888) ;
The following is a complete "Http" request data content.
POST/HTTP/1.1
User-Agent: curl/7.26.0
Host: localhost
Accept: */*
Content-Length: 11
Content-Type: application/x-www-form-urlencoded
Hello World
Four, summary
(1), understand the concept of "Http".
(2), be proficient in using "Http" related APIs.
(3) Pay attention to the details, such as the processing details between "POST, GET".
(4), understanding of "requestListener".
(5), emphasizes a concept: an http request object is a readable stream, and an http response object is a writable stream.

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.

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

How to send task notifications in Quartz In advance When using the Quartz timer to schedule a task, the execution time of the task is set by the cron expression. Now...

How to obtain the parameters of functions on prototype chains in JavaScript In JavaScript programming, understanding and manipulating function parameters on prototype chains is a common and important task...

Analysis of the reason why the dynamic style displacement failure of using Vue.js in the WeChat applet web-view is using Vue.js...


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

WebStorm Mac version
Useful JavaScript development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Linux new version
SublimeText3 Linux latest version

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.