最近与Node项目接触的比较多,故决定介绍一些用到的node模块,并附带一些使用时的经验。
首先用到的一个就是request,当在node中调用其他系统接口或进行一些交互时,所能采用的一种http/https请求方式。
简单示例
var request = require('request');
request('http://www.google.com', function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print the HTML for the Google homepage.
});
流
可以把响应转化成文件流:
request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))
也可以将文件流写入post或put方法,但要使用合适的content-type。
fs.createReadStream('file.json').pipe(request.put('http://mysite.com/obj.json'))
请求也可以传输自己,此时put的header里要有content-type和content-length。
request.get('http://google.com/img.png').pipe(request.put('http://mysite.com/img.png'))
请求会产生响应事件:
request
.get('http://google.com/img.png')
.on('response', function(response) {
console.log(response.statusCode) // 200
console.log(response.headers['content-type']) // 'image/png'
})
.pipe(request.put('http://mysite.com/img.png'))
若要处理错误,则
request
.get('http://mysite.com/doodle.png')
.on('error', function(err) {
console.log(err)
})
.pipe(fs.createWriteStream('doodle.png'))
综合示例:
http.createServer(function (req, resp) {
if (req.url === '/doodle.png') {
if (req.method === 'PUT') {
req.pipe(request.put('http://mysite.com/doodle.png'))
} else if (req.method === 'GET' || req.method === 'HEAD') {
request.get('http://mysite.com/doodle.png').pipe(resp)
}
}
})
pipe可用于http 请求和响应对象。
http.createServer(function (req, resp) {
if (req.url === '/doodle.png') {
var x = request('http://mysite.com/doodle.png')
req.pipe(x)
x.pipe(resp)
}
})
代理:
req.pipe(request('http://mysite.com/doodle.png')).pipe(resp)
表单
application/x-www-form-urlencoded (URL-Encoded Forms)
request.post('http://service.com/upload'