如何从Node.js或Express.js中发出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发送请求。目前,这是一个实验性的功能,所以要小心。

其他回答

你也可以使用Requestify,这是我为nodeJS +编写的一个非常酷且非常简单的HTTP客户端,它支持缓存。

只需对GET方法请求执行以下操作:

var requestify = require('requestify');

requestify.get('http://example.com/api/resource')
  .then(function(response) {
      // Get the response body (JSON parsed or jQuery object for XMLs)
      response.getBody();
  }
);

看看shred。它是由spire创建和维护的节点HTTP客户端。io处理重定向、会话和JSON响应。它非常适合与rest api交互。详见这篇博客文章。

## you can use request module and promise in express to make any request ##
const promise                       = require('promise');
const requestModule                 = require('request');

const curlRequest =(requestOption) =>{
    return new Promise((resolve, reject)=> {
        requestModule(requestOption, (error, response, body) => {
            try {
                if (error) {
                    throw error;
                }
                if (body) {

                    try {
                        body = (body) ? JSON.parse(body) : body;
                        resolve(body);
                    }catch(error){
                        resolve(body);
                    }

                } else {

                    throw new Error('something wrong');
                }
            } catch (error) {

                reject(error);
            }
        })
    })
};

const option = {
    url : uri,
    method : "GET",
    headers : {

    }
};


curlRequest(option).then((data)=>{
}).catch((err)=>{
})

尝试使用简单的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。请求(选项,回调)函数,允许您指定请求方法和其他请求细节。

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文档