Node.js接口
http超文本传输协议
> http.METHODS:解析器支持的HTTP方法列表。 > http.STATUS_CODES:所有标准HTTP响应状态代码的集合,以及每个的简短描述。 例如,http.STATUS_CODES[404] === 'Not Found'。 > http.globalAgent:Agent的全局实例,用作所有HTTP客户端请求的默认值。 > http.validateHeaderName(name[, label]):在调用res.setHeader(name, value)时对提供的name执行低层验证。 > http.validateHeaderValue(name, value):在调用res.setHeader(name, value)时对提供的value执行低层验证。 > http.maxHeaderSize:只读属性,指定HTTP标头的最大允许大小(以字节为单位)。 默认为 16 KiB。 > http.setMaxIdleHTTPParsers(max):设置最大空闲HTTP解析器数。 > http.createServer(options):返回http.Server的新实例 > http.get(options[, callback]) > http.get(url, options):该方法与http.request()唯一的区别是它默认设置方法为 GET 并自动调用 req.end()。 > http.request(options[, callback]) > http.request(url, options): 返回http.ClientRequest类的实例。 ClientRequest实例是可写流。 如果使用POST请求上传文件,则写入ClientRequest对象。 #### `http.createServer()` ```js const http = require('node:http'); // Create a local server to receive data from const server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ data: 'Hello World!', })); }); server.listen(8000); const server = http.createServer(); server.on('request', (request, res) => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ data: 'Hello World!', })); }); ``` #### `http.request()` ```js const http = require('node:http'); const postData = JSON.stringify({ 'msg': 'Hello World!', }); const options = { hostname: 'www.google.com', port: 80, path: '/upload', method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(postData), }, }; const req = http.request(options, (res) => { res.setEncoding('utf8'); res.on('data', (chunk) => { console.log(`BODY: ${chunk}`); }); res.on('end', () => { console.log('No more data in response.'); }); }); req.on('error', (e) => { console.error(`problem with request: ${e.message}`); }); // Write data to request body req.write(postData); req.end(); //使用 http.request() 必须始终调用 req.end() 来表示请求的结束 - 即使没有数据写入请求正文 ``` #### `http.get()` ```js http.get('http://localhost:8000/', (res) => { const { statusCode } = res; const contentType = res.headers['content-type']; let error; if (statusCode !== 200) { error = new Error('Request Failed.\n' + `Status Code: ${statusCode}`); } else if (!/^application\/json/.test(contentType)) { error = new Error('Invalid content-type.\n' + `Expected application/json but received ${contentType}`); } if (error) { console.error(error.message); // Consume response data to free up memory res.resume(); return; } res.setEncoding('utf8'); let rawData = ''; res.on('data', (chunk) => { rawData += chunk; }); res.on('end', () => { try { const parsedData = JSON.parse(rawData); console.log(parsedData); } catch (e) { console.error(e.message); } }); }).on('error', (e) => { console.error(`Got error: ${e.message}`); }); // Create a local server to receive data from const server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ data: 'Hello World!', })); }); server.listen(8000); ``` #### http.Server类: - > **事件:'checkContinue':**每次收到带有 HTTP Expect: 100-continue 的请求时触发。 如果未监听,则服务器将根据需要自动响应 100 Continue。 > **事件:'checkExpectation':**每次收到带有 HTTP Expect 的请求时触发,其中值不是 100-continue。 如果未监听,则自动响应 417 Expectation Failed。 > **事件:'clientError':**如果客户端连接触发 'error' 事件,则会在此处转发。 此事件的监听器负责关闭/销毁底层套接字。 > **事件:'close':**服务器关闭时触发。 > **事件:'connect':**每次客户端请求 HTTP CONNECT 方法时触发。 如果未监听此事件,则请求 CONNECT 方法的客户端将关闭其连接。 > **事件:'connection':**当建立新的 TCP 流时会触发此事件。 socket 通常是 net.Socket 类型的对象。 通常用户不会想访问这个事件。 > **事件:'dropRequest':**当套接字上的请求数达到 server.maxRequestsPerSocket 的阈值时,服务器会丢弃新的请求并触发 'dropRequest' 事件,然后将 503 发送给客户端。 > **事件:'request':**每次有请求时触发。 每个连接可能有多个请求(在 HTTP Keep-Alive 连接的情况下)。 > **事件:'upgrade':**每次客户端请求 HTTP 升级时触发。 监听此事件是可选的,客户端不能坚持协议更改。 - > **server.close([callback]):**停止服务器接受新连接并关闭连接到该服务器的所有未发送请求或等待响应的连接。 > **server.closeAllConnections():**关闭所有连接到此服务器的连接。 > **server.closeIdleConnections():**关闭连接到此服务器的所有未发送请求或等待响应的连接。 - > **server.listen():**启动 HTTP 服务器监听连接。 > **server.listening:** 指示服务器是否正在监听连接 - > **server.maxHeadersCount:**限制最大传入标头计数。 如果设置为 0,则不会应用任何限制。默认2000。 > **server.maxRequestsPerSocket:**关闭保持活动的连接之前,套接字可以处理的最大请求数。默认值: 0(无限制) - > **server.timeout:**假定套接字超时之前不活动的毫秒数。 默认值: 0(无超时) > **server.setTimeout(msecs):**设置套接字的超时值,并在服务器对象上触发 'timeout' 事件,如果发生超时,则将套接字作为参数传入。默认值: 0(无超时) > **server.headersTimeout:**限制解析器等待接收完整 HTTP 标头的时间。默认值60000 > **server.requestTimeout:**设置从客户端接收整个请求的超时值(以毫秒为单位)。默认值: 300000 > **server.keepAliveTimeout:**在完成写入最后一个响应之后,在套接字将被销毁之前,服务器需要等待额外传入数据的不活动毫秒数。 默认值: 5000(5 秒)。 - > **server[Symbol.asyncDispose] ():**调用 server.close() 并返回一个在服务器关闭时履行的 promise。 #### http.Agent类: - > **new Agent([options]):**自定义的 http.Agent 实例 > **agent.createConnection(options[, callback]):**生成用于 HTTP 请求的套接字/流 > **agent.keepSocketAlive(socket):**此方法可以被特定的 Agent 子类覆盖。 如果此方法返回假值,则套接字将被销毁,而不是将其持久化以供下一个请求使用。 > **agent.destroy():**销毁代理当前正在使用的所有套接字。通常没有必要这样做。 如果使用启用了 keepAlive 的代理,则最好在不再需要代理时显式关闭该代理。 否则套接字可能会在服务器终止它们之前保持打开很长时间。 > **agent.reuseSocket(socket, request):**当 socket 由于保持活动选项而持久化后附加到 request 时调用。 - > **agent.getName([options]):**获取一组请求选项的唯一名称,以确定是否可以重用连接。 > agent.maxFreeSockets:默认设置为 256。 对于启用了 keepAlive 的代理,这将设置在空闲状态下将保持打开的最大套接字数量。 > **agent.maxSockets:**默认设置为 Infinity。 确定代理可以为每个来源打开多少个并发套接字。 来源是 agent.getName() 的返回值。 > **agent.maxTotalSockets:**默认设置为 Infinity。 确定代理可以打开多少个并发套接字。 与 maxSockets 不同,此参数适用于所有来源。 - > **agent.freeSockets:**当启用 keepAlive 时,包含当前等待代理使用的套接字数组的对象。 不要修改。 > **agent.requests:**包含尚未分配给套接字的请求队列的对象。 不要修改。 > **agent.sockets:**包含代理当前正在使用的套接字数组的对象。 不要修改。
顶部
收展
底部
[TOC]
目录
CommonJS 模块
package包模块
全局对象
http超文本传输协议
util实用工具
buff缓冲区
断言测试
EventEmitter事件
child_process子进程
相关推荐
Node.js教程:新手入门
Node.js:ExpressWeb
朴灵《深入浅出 Node.js》