[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 響應結果

# 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();
~~~