Node的http模块提供了两个函数
- http.request
- http.get
功能是作为客户端向HTTP 服务器发起请求,http模块可以作为服务器也可作为客户端,Node经常会需要访问外部服务器来实现功能,可以使用这两个函数。
http.request
接受两个参数,option 是一个类似关联数组的对象,表示请求的参数,callback是请求的回调函数 。 http.request 返回一个 http.ClientRequest 的实例 。
常用的options有:
var options = {
protocol:'',//协议,默认是http协议
host:'',//请求地址或者IP地址,默认是localhost
hostname:'http://blog.hsblogs.com/index.php?m=Home&c=Test&a=index'
port:'80',//端口号
method:'get', //http指定的请求方式
path:'/data',//请求路径,默认为'/' ,可以包括queryString字符串'/index.php?m=Home&c=Test&a=index'
headers:{
'Content-Type': 'application/json',
}
};
使用实例 get请求的
var http = require('http');
var querystring = require('querystring')
var express = require('express');
var app = express();
app.listen('1231',function () {
console.log('1231 is listen');
})
var options = {
// protocol:'',//协议,默认是http协议
// host:'',//请求地址或者IP地址,默认是localhost
// hostname:'http://blog.hsblogs.com/index.php?m=Home&c=Test&a=index'
// port:'80',//端口号
// method:'get', http指定的请求方式
// path:'',请求路径,默认为'/' ,可以包括queryString字符串'/index.php?m=Home&c=Test&a=index'
// headers:{ 'Content-Type': 'application/json', } //
host: 'blog.hsblogs.com',
port:'80',
path:'/json.php'
};
var req = http.request(options,function(res){
console.log('STATUS:' + res.statusCode);
// console.log('HEADERS:' + JSON.stringify(res.headers));
// res.setEncoding('utf8');
res.on('data',function(chunk){
//chunk 为 buffer字符串,如果要使用buffer对象的话,需要转
console.log( typeof chunk);//string
console.log(JSON.parse(chunk));
// console.log('BODY' + chunk);
});
});
req.on('response',function(){});
req.on('connect',function(){});
req.on('socket',function(){});
req.on('upgrade',function(){});
req.on('continue',function(){})
//如果在请求过程中出现了错误(可能是DNS解析、TCP的错误、或者HTTP解析错误),返回的请求对象上的'error'的事件将被触发。
req.on('error',function(e){
console.log(e.message);
});
/**
* 源API:request.write(chunk, [encoding])
* 说明:发送正文中的一块。用户可以通过多次调用这个方法将请求正文以流的方式发送到服务器。此种情况建议在建立请求时使用['Transfer-Encoding', 'chunked']请求头。
* @param {Object or String} chunk 参数chunk应当是一个整数数组或字符串。
* @param {String} encoding 参数encoding是可选的,仅在chunk为字符串时可用。
*/
req.write('data\n');
/**
* 源API:request.end(chunk, [encoding])
* 说明:完成本次请求的发送。如果正文中的任何一个部分没有来得及发送,将把他们全部刷新到流中。如果本次请求是分块的,这个函数将发出结束字符'0\r\n\r\n'。如果使用参数data,就等于在调用request.write(data, encoding)之后紧接着调用request.end()。
* @param {Object or String} chunk 参数chunk应当是一个整数数组或字符串。
* @param {String} encoding 参数encoding是可选的,仅在chunk为字符串时可用。
* example: req.end(),req.end('data\n'),req.end('data','utf8'),req.end(chunk)
*/
req.end();
/**
* 阻止一个请求。(v0.3.8中新增的方法。)
*/
// req.abort();
/**
* 源API:request.setTimeout(timeout, [callback])
* 说明:一旦给这个请求分配的是一个socket时此函数会被调用
* @param {Number} timeout 毫秒
* @param {Function} callback 回到函数
*/
// req.setTimeout(1000,function(){});
/**
* 源API :request.setNoDelay([noDelay])
* 说明:默认有一定的延迟,设置为0表示无延迟
* @param {Number} noDelay
*/
// req.setNoDelay(0)
/**
* 源API:request.setSocketKeepAlive([enable], [initialDelay])
* 类似同上
*/
post请求
var querystring = require('querystring');
var http = require('http');
// 创建一个post数据的字符串
var post_data = querystring.stringify({
'userId' : '1121',
'username': 'Manster',
'age': '22',
});
var post_options = {
host: 'closure-compiler.appspot.com',
port: '80',
path: '/compile',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(post_data)
}
};
var post_req = http.request(post_options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('Response: ' + chunk);
});
});
// 发送post数据
post_req.write(post_data);
post_req.end();
http.get
因为请求大多数都是get请求,所以http模块提供了这个便利的方法,这个和http.request()方法唯一的区别是http.get自动将请求方法设为了 GET 请求,同时不需要手动调用 req.end()
var http = require('http');
http.createServer(function(req,res){
}).listen(3000);
http.get(options, function (res) {
var data = "";
//此事件会发射多次,因为chunk为buffer,会分批快速传输
res.on("data", function (chunk) {
// 拼接我们的数据
data += chunk;
});
//end事件只触发一次,在数据接受完成之后触发
res.on("end", function () {
data = JSON.parse(data);
console.log(data);
});
});
文章评论