Node模块(一)——request

最近与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'
  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值