nodejsApi之http

長空發表於2019-02-16

基於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

  1. http.METHODS:常量,http的方法列表如get,post,put,delete等

  2. http.STATUS_CODES:常量,http的狀態碼列表如200,500等。

  3. http.createServer([requestListener]):建立http.Server類

  4. http.Server:http.createServer的返回值。

  5. http.ServerResponse:res。

  6. http.IncomingMessage:req

  7. http.get(options[, callback]):

  8. http.request(options[, callback]):

  9. http.ClientRequest:http.get和http.request的返回值

  10. http.Agent:http代理。

  11. http.globalAgent:

3. http.server

4. http.IncomingMessage

  1. message.headers: json物件

  2. message.httpVersion

  3. message.method

  4. message.rawHeaders:字串陣列

  5. message.url

  6. message.statusCode

  7. message.statusMessage

5. http.ServerResponse

  1. response.writeHead(statusCode, statusMessage)

  2. response.write(chunk, encoding)

  3. response.end(data[, callback])
    // 1相當於下面3個

  4. response.setHeader(name, value)

  5. response.statusCode

  6. 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 + `】
`);
        });
    });
});

相關文章