原文地址:http://samwize.com/2013/08/31/simple-http-get-slash-post-request-in-node-dot-js/
频繁用到,频繁搞不明白,特此记录。通过request实现
get 请求 (http://127.0.0.1:8009/xxx/xxx/x?loginName=test)
var name = req.body.loginData
var headers = {
'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/x-www-form-urlencoded'
}
// Configure the request
var options = {
url: 'http://127.0.0.1:8009/xxx/xxx/x',
method: 'GET',
headers: headers,
qs: {'loginName': name}//多参数继续增加'XXX':XX
}
// Start the request
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
// Print out the response body
console.log(body);
res.json(body);
}
})
post请求
var formData = querystring.stringify(req.body);
var headers ={
'User-Agent':'Super Agent/0.01',
'Content-Type': 'application/x-www-form-urlencoded'
}
var options = {
url:'http://127.0.0.1:8009/xxx/xxx/x',
method:'POST',
headers:headers,
form:formData
}
request(options,function(error,response,body){
if(!error && response.statusCode == 200){
console.log(response.headers);
console.log("网页返回:"+body+"\n ");
}else{
res.direct(response.headers.location);
}
})