多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] >[warning] 说明:本文档只说明使用频繁的知识点,有关对应知识的所有具体内容可查看对应的 API 连接 >[success] Node.js 的 HTTP API 都非常底层。 它仅进行流处理和消息解析,所有的高层功能都要通过它的接口实现 // 一个服务器案例 ~~~ const http = require('http'); const server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'application/json' }); const arr = [{ id: 0, name: '1' }, { id: 1, name: '2' }] const obj = { data: arr }; res.write(JSON.stringify(obj)); res.end(); }) server.listen(3030, 'localhost'); ~~~ // 请求 localhost:3030 响应结果 ![](https://img.kancloud.cn/d8/f0/d8f0475bd634eedf4388b255612222db_292x219.png) # 1. http.createServer([options][, requestListener]) 更多内容查看 [http://nodejs.cn/api/http.html#http\_http\_createserver\_options\_requestlistener](http://nodejs.cn/api/http.html#http_http_createserver_options_requestlistener) * http模块创建服务器的方法 * 返回 http.server 的实例 > requestListener是一个自动添加到 http.server.request 事件的函数。 # 2. http.server 类 继承自:[net.server()](http://nodejs.cn/s/gBYjux) ## 2.1 常用的事件 ### 2.1.1 server.listen() 启动 HTTP 服务器监听连接,与[`net.Server`](http://nodejs.cn/s/gBYjux)中的[`server.listen()`](http://nodejs.cn/s/xGksiu)相同。 ### 2.1.2 server.request(request, response) > 参数详情可查看[http://nodejs.cn/api/http.html#http\_event\_request](http://nodejs.cn/api/http.html#http_event_request) 在每次有请求时触发 。 ### 2.1.3 server.setTimeout([msecs][, callback]) msecs: 默认超时设置 2 分钟: 120000 callback: 返回 http.server ### 2.1.4 server.close([callback]) 停止服务器接受新连接 ## 2.2 常用的属性 ### 2.2.1 server.listening 表明服务器是否正在监听连接 ### 2.2.2 server.timeout 超时时间;更改此值仅影响到服务器的新连接,而不影响任何现有连接 # 3. http.IncomingMessage 类 * 实例由 http.server 或 http.ClientRequest 创建,并分别作为 http.server.request 的第一个参数和 http.ClientRequest 的第一个参数 * 由于实例对象的创建者不一定,在api中,该实例的属性或方法用 message 表示 > 更多属性可查看 [http.IncomingMessage 类](http://nodejs.cn/api/http.html#http_class_http_incomingmessage) ## 3.1 常用属性 ### 3.1.1 message.complete 在收到并成功解析完整的 HTTP 消息时为 true ~~~ // 官网的案例 const req = http.request({ host: '127.0.0.1', port: 8080, method: 'POST' }, (res) => { res.resume(); res.on('end', () => { if (!res.complete) console.error( '消息仍在发送时终止了连接'); }); }); ~~~ ### 3.1.2 message.headers * 请求或相应的消息头对象 ~~~ // 官网的案例 // 打印类似以下: // // { 'user-agent': 'curl/7.22.0', // host: '127.0.0.1:8000', // accept: '*/*' } console.log(request.headers); ~~~ # 4. http.ServerResponse 类 由 HTTP 服务器在内部创建,作为第二个参数传递给 http.server.request > 更多属性与方法可查看 [http.ServerResponse 类](http://nodejs.cn/api/http.html#http_class_http_serverresponse) ## 4.1 常用属性 ### 4.1.1 response.writableFinished 在触发 response.finish 事件之前,所有数据都已刷新到底层的系统,则为`true`。 ## 4.2 常用方法 ### 4.1.2 response.writeHead 向请求的客户端发送响应头 ### 4.1.3 response.write(data, [encoding]) 向请求客户端发送相应内容,data是buffer或字符串,encoding为编码 ### 4.1.3 response.end 结束响应,告知用户所有发送已经完成,当所有要返回的内容发送完毕,该函数必须被调用一次,如果不调用,客户端永远处于等待状态 # 5. http.request(url[, options][, callback]) > nodejs 可以模仿客户端向服务器发送请求,除了http.request 还有 http.get ~~~ // 官网的案例 const postData = querystring.stringify({ 'msg': '你好世界' }); const options = { hostname: 'nodejs.cn', port: 80, path: '/upload', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': Buffer.byteLength(postData) } }; const req = http.request(options, (res) => { console.log(`状态码: ${res.statusCode}`); console.log(`响应头: ${JSON.stringify(res.headers)}`); res.setEncoding('utf8'); res.on('data', (chunk) => { console.log(`响应主体: ${chunk}`); }); res.on('end', () => { console.log('响应中已无数据'); }); }); req.on('error', (e) => { console.error(`请求遇到问题: ${e.message}`); }); // 将数据写入请求主体。 req.write(postData); req.end(); ~~~