当前位置:首页 > npm-request

npm-request

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

Request - Simplified HTTP client

request是一款简化http client请求的工具,同时它支持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.
});

响应流Stream

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

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

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

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

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

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)

简单的表单提交方式:

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

multipart/form-data (Multipart Form Uploads)

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

var FormData = require('form-data');
var fs = require('fs');

var form = new FormData();
form.append('my_field', 'my value');
form.append('my_buffer', new Buffer(10));
form.append('my_file', fs.createReadStream('/foo/bar.jpg'));

然后调用request请求

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

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

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