当前位置:首页 > npm-request

npm-request

发布于 2018-04-10 阅读 807 次 NodeJs

Request - Simplified HTTP client

request是一款简化http client请求的工具,同时它支持https和重定向

  1. var request = require('request');
  2. request('http://www.google.com', function (error, response, body) {
  3. console.log('error:', error); // Print the error if one occurred
  4. console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
  5. console.log('body:', body); // Print the HTML for the Google homepage.
  6. });

响应流Stream

你可以将响应流导入到一个文件

  1. request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))

你也可以将一个文件流,用put或者post请求发送出去。此方法还将检查文件扩展名,将文件扩展名映射到content-types(在本例中为application/JSON),并在提交请求中使用适当的内容类型(如果头文件没有提供)。

  1. fs.createReadStream('file.json').pipe(request.put('http://mysite.com/obj.json'))

request也可以把自己请求回来的stream再pipe出去,会继承上一次请求的headers

  1. request.get('http://google.com/img.png').pipe(request.put('http://mysite.com/img.png'))

Forms

request支持application/x-www-form-urlencoded 和 multipart/form-data两种表单提交方式

application/x-www-form-urlencoded(URL-Encoded)

简单的表单提交方式:

  1. request.post('http://service.com/upload', {form:{key:'value'}})
  2. // or
  3. request.post('http://service.com/upload').form({key:'value'})
  4. // or
  5. request.post({url:'http://service.com/upload', form: {key:'value'}}, function(err,httpResponse,body){ /* ... */ })

multipart/form-data (Multipart Form Uploads)

带有文件上传的时候使用这种方式
首先创建一个formdata需要引入另一个npm依赖form-data

  1. var FormData = require('form-data');
  2. var fs = require('fs');
  3. var form = new FormData();
  4. form.append('my_field', 'my value');
  5. form.append('my_buffer', new Buffer(10));
  6. form.append('my_file', fs.createReadStream('/foo/bar.jpg'));

然后调用request请求

  1. request.post({url:'http://service.com/upload', formData: formData}, function optionalCallback(err, httpResponse, body) {
  2. if (err) {
  3. return console.error('upload failed:', err);
  4. }
  5. console.log('Upload successful! Server responded with:', body);
  6. });

或者直接用request的r,会在下一次事件循环开始之前改变数据,调用form()会清空之前的formdata

  1. // NOTE: Advanced use-case, for normal use see 'formData' usage above
  2. var r = request.post('http://service.com/upload', function optionalCallback(err, httpResponse, body) {...})
  3. var form = r.form();
  4. form.append('my_field', 'my_value');
  5. form.append('my_buffer', new Buffer([1, 2, 3]));
  6. form.append('custom_file', fs.createReadStream(__dirname + '/unicycle.jpg'), {filename: 'unicycle.jpg'});