基於v6.10.3版本
1. 基本示例
var http = require(`http`);
var server = http.createServer((req,res)=>{
res.write(`hello world`);
res.write(req.constructor.name); // IncomingMessage
res.write(res.constructor.name); // ServerResponse
res.end();
});
server.listen(3000);
2. http
-
http.METHODS:常量,http的方法列表如get,post,put,delete等
-
http.STATUS_CODES:常量,http的狀態碼列表如200,500等。
-
http.createServer([requestListener]):建立http.Server類
-
http.Server:http.createServer的返回值。
-
http.ServerResponse:res。
-
http.IncomingMessage:req
-
http.get(options[, callback]):
-
http.request(options[, callback]):
-
http.ClientRequest:http.get和http.request的返回值
-
http.Agent:http代理。
-
http.globalAgent:
3. http.server
4. http.IncomingMessage
-
message.headers: json物件
-
message.httpVersion
-
message.method
-
message.rawHeaders:字串陣列
-
message.url
-
message.statusCode
-
message.statusMessage
5. http.ServerResponse
-
response.writeHead(statusCode, statusMessage)
-
response.write(chunk, encoding)
-
response.end(data[, callback])
// 1相當於下面3個 -
response.setHeader(name, value)
-
response.statusCode
-
response.statusMessage
var http = require(`http`);
var server = http.createServer((req,res)=>{
// writeHead解除安裝write後面
res.writeHead(200,{`content-type`:`text/html;charset=utf-8`});
res.write(`hello world`+`<br/>`);
res.write(`你好 世界`);
res.end();
});
server.listen(3000);
6. http.request(options[, callback]):
http請求,第一個引數options可以新增請求引數,第二個引數是回撥函式。
var postData = querystring.stringify({
`msg` : `Hello World!`
});
var options = {
hostname: `www.google.com`,
port: 80,
path: `/upload`,
method: `POST`,
headers: {
`Content-Type`: `application/x-www-form-urlencoded`,
`Content-Length`: Buffer.byteLength(postData)
}
};
var req = http.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding(`utf8`);
res.on(`data`, (chunk) => {
console.log(`主體: ${chunk}`);
});
res.on(`end`, () => {
console.log(`響應中已無資料。`);
});
});
// 錯誤監聽
req.on(`error`, (e) => {
console.log(`請求遇到問題: ${e.message}`);
});
// 寫入資料到請求主體
req.write(postData);
// http.request()必須總是呼叫req.end()來表明請求已經結束,即使沒有資料被寫入請求主體
req.end();
7. http.get(options[, callback])
因為大多數請求都是GET請求且不帶主體,所以Node.js提供了這個便捷的方法。該方法與 http.request() 唯一的區別是它設定請求方法為 GET 且自動呼叫 req.end()。
var http = require(`http`);
http.get(`http://localhost:3000`,res=>{
console.log(res);
});
8. http.get實現爬蟲 爬取百度貼吧
var http = require(`http`);
var cheerio = require(`cheerio`);
var url = "http://tieba.baidu.com/f?kw=%CE%E4%B0%B2&fr=index";
http.get(url, function(res) {
var html = ``;
res.on(`data`, function(data) {
html += data;
});
res.on(`end`, function() {
var $ = cheerio.load(html);
var infos = []; // var info = {title:``,author:``};
var lis = $(`.j_thread_list`);
lis.each(function(index, element) {
// this 是li
// element 是li 同this
var item = $(this);
var title = item.find(`div.threadlist_title a`).text().trim();
var author = item.find(`div.threadlist_author a`).text().trim();
infos.push({
title: title,
author,
author
});
})
infos.forEach(function(item, index, array) {
// array這裡和item一樣 // index是序列號
console.log(index + 1 + `. ` + item.title + `【` + item.author + `】
`);
});
});
});