PJCHENder 未整理筆記

[npm] requestJS

2017-12-28

[npm] requestJS

@(NodeJS)[npm, JavaScript]

keywords: ajax, http, request, 爬蟲

request @ github

使用

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* 基本的 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);
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* 使用設定
**/
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)
})

設定預設值

1
2
3
4
5
6
7
8
9
let request = require('request')

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

安裝

1
$ npm install request

掃描二維條碼,分享此文章