目的:使用Nodejs向其他web服务器发送请求
HTTP已经演变成并非仅用于交换最终渲染,展示给用户的标记文本(如HTML),而且它还是服务器在不同网络环境传递数据的一种方式。同时,JSON因其语法衍生自JavaScript线性对象,也快速成为了HTTP默认的标准数据格式,这也是Node.js在服务端的优势之一。
创建模块
// package.json
{
"name": "twitter-client",
"description": "An HTTP twitter client ",
"version": "0.0.1"
}
发送一个简单的HTTP请求
典型的HTTP服务器:
// server.js
require('http').createServer(function (req, res) {
res.writeHead(200);
res.end('Hello World');
}).listen(3000);
一个客户端来获取该响应,并将其在控制台以彩色的形式打印出来:
// client.js
require('http').request({
host: '127.0.0.1',
port: 3000,
url: '/',
method: 'GET'
},function (res) {
var body = '';
res.setEncoding('utf-8');
res.on('data',function(chunk) {
body += chunk;
});
res.on('end',function() {
console.log('\n We got: \033[39m\n');
});
}).end();
request方法,此方法用于初始化一个新的http.Client Request对象。
注意,我们收集信息块的方式和此前在服务器端收集客户端信息快的方式一样。连接的远程服务器会返回不同的数据块,我们需要将他们全部收集才能得到完整的响应。当然,也可能所有的数据在一个data事件中都到达了,不过我们无从得知。
除此之外,还要通过响应对象上的setEncoding将编码设置为utf8。
发送数据
注意,在之前的例子中,调用完request之后,还需要调用end。
原因是在创建完一个请求之后,在发送给服务器之前还可以和request对象进行交互。
发送一个数据给服务器的例子:
// server.js
// 服务端处理表单:
var qs = require('querystring');
require('http').createServer(function (req, res) {
var body = '';
req.on('data', function(chunk) {
body += chunk;
});
req.on('end',function() {
res.writeHead(200);
res.end('Done');
console.log('\n got name \033[90m' + qs.parse(body).name + '\033[39m\n');
});
}).listen(3000);
客户端输入名字:
// client.js
var http = require('http'),
qs = require('querystring');
function send(theName) {
http.request({
host: '127.0.0.1',
port: 3000,
url: '/',
method: 'POST'
},function (res) {
res.setEncoding('utf8');
res.on('end',function() {
console.log('\n request complete! \033[39m\n');
process.stdout.write('\n your name: ');
});
}).end(qs.stringify({name: theName}));
}
process.stdout.write('\n your name: ');
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', function(name) {
send(name.replace('\n',''));
});
结果,输入的名字会在服务器中显示。
superagent
superagent模块通过扩展response对象,为其添加一些有用的扩展来解决请求数据对象编码问题。
var request = require('superagent');
request.get('')
.send({q : 'hh'})
.set('Date:', new Date())
.end(function(res){console.log(res.body);});
上述为链式调用,通过set方法设置了请求的Date头信息。
UP工具
up,一个命令行工具,每次修改代码后up就会自动重启服务器进程让修改立即生效。注意,要使用up,必须确保模块要将通过调用createServer返回的http.Server实例暴露出来。