node中的request模塊(http.get封裝版)


1.下載並引入request

cnpm install request --save;
const request = require("request");

2.基本使用

request({
    url: url,//請求路徑
    method: "POST",//請求方式,默認為get
    headers: {//設置請求頭
        "content-type": "application/json",
    },
    body: JSON.stringify(requestData)//post參數字符串
}, function(error, response, body) {
    if (!error && response.statusCode == 200) {
    }
});

栗子:

1.抓取內容
var request = require('request');
request('https://www.baidu.com', function (error, response, body) {
       console.log(body)//打印百度首頁html內容
})
or
request({url:'https://www.baidu.com'}, function (error, response, body) {
       console.log(body)//打印百度首頁html內容
})
2.抓取文件
request('https://www.baidu.com/img/bd_logo1.png').pipe(fs.createWriteStream('a.png'))
//抓取百度logo並保存到本地
fs.createReadStream('pic.jpg').pipe(request.put('http://veb.com/upload'))
//讀取流pipe上傳

擴展:

cheerio 
//npm install cheeriovar  cheerio = require('cheerio');
var  $ = cheerio.load('<ul id="fruits">...</ul>');//jquery 一樣的操作

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM