Request - 简化HTTP客户端

jopen 10年前

使用超级简单

Request 被设计为尽可能最简单的方法,使HTTP调用。它支持HTTPS和默认遵循重定向。

var request = require('request');  request('http://www.google.com', function (error, response, body) {    if (!error && response.statusCode == 200) {      console.log(body) // Print the google web page.    }  })

Streaming

您可以传输到一个文件流的任何回应。

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

You can also stream a file to a PUT or POST request. This method will also check the file extension against a mapping of file extensions to content-types (in this case application/json) and use the proper content-type in the PUT request (if the headers don’t already provide one).

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

Request can also pipe to itself. When doing so, content-type and content-length are preserved in the PUT headers.

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

Request emits a "response" event when a response is received. The response argument will be an instance of http.IncomingMessage.

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'))

Now let’s get fancy.

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)      }    }  })

You can also pipe() from http.ServerRequest instances, as well as to http.ServerResponse instances. The HTTP method, headers, and entity-body data will be sent. Which means that, if you don't really care about security, you can do:

http.createServer(function (req, resp) {    if (req.url === '/doodle.png') {      var x = request('http://mysite.com/doodle.png')      req.pipe(x)      x.pipe(resp)    }  })

And since pipe() returns the destination stream in ≥ Node 0.5.x you can do one line proxying. :)

req.pipe(request('http://mysite.com/doodle.png')).pipe(resp) 

Also, none of this new functionality conflicts with requests previous features, it just expands them.

var r = request.defaults({'proxy':'http://localproxy.com'})    http.createServer(function (req, resp) {    if (req.url === '/doodle.png') {      r.get('http://google.com/doodle.png').pipe(resp)    }  })

You can still use intermediate proxies, the requests will still follow HTTP forwards, etc.


项目主页:http://www.open-open.com/lib/view/home/1414049067231