跳至主要内容

[note] request-js 筆記

request @ github

使用

/**
* 基本的 request 使用
**/
request('http://www.google.com', function (error, response, body) {
// Print the error if one occurred
console.log('error:', error);

// Print the response status code if a response was received
console.log('statusCode:', response && response.statusCode);

// Print the HTML for the Google homepage.
console.log('body:', body);
});
/**
* 使用設定
**/
var options = {
url: 'http://www.pjchender.com',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Cookie: 'put cookie here',
},
qs: {
s: 'query_string',
},
form: {
name: 'foo',
address: 'bar',
},
formData: {
strTargetField: 'COUNTY',
},
};

request(options, (err, res, body) => {
if (err) {
throw new Error(err);
}
let $ = cheerio.load(body);
console.log(body);
});

設定預設值

let request = require('request');

request = request.defaults({
jar: true, // 將前一次 request 得到的 Cookie 自動套用到後面的 request 中
headers: {
cookie: 'this is cookie',
'user-agent': 'this is user agent',
},
});

安裝

$ npm install request