如何从Node.js或Express.js中发出HTTP请求?我需要连接到另一个服务。我希望调用是异步的,并且回调包含远程服务器的响应。


当前回答

Request和Superagent是非常好的库。

注意:请求已弃用,使用风险自负!

使用要求:

var request=require('request');

request.get('https://someplace',options,function(err,res,body){
  if(err) //TODO: handle err
  if(res.statusCode === 200 ) //etc
  //TODO Do something with response
});

其他回答

尝试使用简单的http。Get (options, callback)函数在node.js:

var http = require('http');
var options = {
  host: 'www.google.com',
  path: '/index.html'
};

var req = http.get(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));

  // Buffer the body entirely for processing as a whole.
  var bodyChunks = [];
  res.on('data', function(chunk) {
    // You can process streamed parts here...
    bodyChunks.push(chunk);
  }).on('end', function() {
    var body = Buffer.concat(bodyChunks);
    console.log('BODY: ' + body);
    // ...and/or process the entire body here.
  })
});

req.on('error', function(e) {
  console.log('ERROR: ' + e.message);
});

还有一个通用的http。请求(选项,回调)函数,允许您指定请求方法和其他请求细节。

对于任何想要在NodeJS中发送HTTP请求的库的人来说,axios也是一个不错的选择。它支持Promises:)

Install (npm)

示例GET请求:

const axios = require('axios');

axios.get('https://google.com')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })

Github页面


更新10/02/2022

Node.js在实验模式下集成了v17.5.0中的fetch。现在,您可以像在客户端一样使用fetch发送请求。目前,这是一个实验性的功能,所以要小心。

Unirest是我遇到的用于从Node发出HTTP请求的最好的库。它的目标是成为一个多平台框架,所以如果你需要在Ruby、PHP、Java、Python、Objective C、. net或Windows 8上使用HTTP客户端,学习它在Node上的工作方式会对你很有帮助。据我所知,unirest库大多是由现有的HTTP客户端支持的(例如,在Java上,Apache的HTTP客户端,在Node上,Mikeal的Request库)——unirest只是在上面放了一个更好的API。

下面是Node.js的一些代码示例:

var unirest = require('unirest')

// GET a resource
unirest.get('http://httpbin.org/get')
  .query({'foo': 'bar'})
  .query({'stack': 'overflow'})
  .end(function(res) {
    if (res.error) {
      console.log('GET error', res.error)
    } else {
      console.log('GET response', res.body)
    }
  })

// POST a form with an attached file
unirest.post('http://httpbin.org/post')
  .field('foo', 'bar')
  .field('stack', 'overflow')
  .attach('myfile', 'examples.js')
  .end(function(res) {
    if (res.error) {
      console.log('POST error', res.error)
    } else {
      console.log('POST response', res.body)
    }
  })

您可以直接跳转到Node文档

Request和Superagent是非常好的库。

注意:请求已弃用,使用风险自负!

使用要求:

var request=require('request');

request.get('https://someplace',options,function(err,res,body){
  if(err) //TODO: handle err
  if(res.statusCode === 200 ) //etc
  //TODO Do something with response
});

这个版本是基于bryanmac函数最初提出的,它使用承诺,更好的错误处理,并在ES6中重写。

let http = require("http"),
    https = require("https");

/**
* getJSON:  REST get request returning JSON object(s)
* @param options: http options object
*/
exports.getJSON = function (options) {
    console.log('rest::getJSON');
    let reqHandler = +options.port === 443 ? https : http;

    return new Promise((resolve, reject) => {
        let req = reqHandler.request(options, (res) => {
            let output = '';
            console.log('rest::', options.host + ':' + res.statusCode);
            res.setEncoding('utf8');

            res.on('data', function (chunk) {
                output += chunk;
            });

            res.on('end', () => {
                try {
                    let obj = JSON.parse(output);
                    // console.log('rest::', obj);
                    resolve({
                        statusCode: res.statusCode,
                        data: obj
                    });
                }
                catch (err) {
                    console.error('rest::end', err);
                    reject(err);
                }
            });
        });

        req.on('error', (err) => {
            console.error('rest::request', err);
            reject(err);
        });

        req.end();
    });
};

因此,您不必传入回调函数,而是getJSON()返回一个承诺。在下面的例子中,该函数在ExpressJS路由处理程序中使用

router.get('/:id', (req, res, next) => {
    rest.getJSON({
        host: host,
        path: `/posts/${req.params.id}`,
        method: 'GET'
    }).then(({ statusCode, data }) => {
        res.json(data);
    }, (error) => {
        next(error);
    });
});

当出现错误时,它将错误委托给服务器错误处理中间件。