基于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 + '】\n');
        });
    });
});

唯见长江天际流
827 声望11 粉丝

黄鹤楼送孟浩然之广陵