NodeJS表达make get请求

NodeJS express make get request

本文关键字:请求 get make 表达 NodeJS      更新时间:2023-09-26

是否有可能使用express作为客户端模块,使http请求到另一个服务器?

目前我是这样提出请求的:

var req = http.get({host, path}, function(res) {
    res.on('data', function(chunk) {
        ....
    }
}

这个太笨重了。Express作为服务器模块使用起来非常舒适。我想有一种简单的方法来发出get请求,那就是使用express。我不喜欢快速api,我在那里什么也没找到。

如果你想要简单的请求,不要使用express模块,但是例如request:

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

使用request的答案有点过时,因为它自2019年以来已被弃用。

使用Node内置的https.request()方法(Node文档)确实感觉有点"臃肿"。(IMO),但你可以根据自己的需要轻松地简化它。如果您的用例如您所描述的那样,那么您所需要的就是:

function httpGet(host, path, chunkFunction) {
    http.get({ host, path }, (res) => res.on('data', chunkFunction));
}

然后在任何地方实现它,如:

const handleChunk = (chunk) => { /* ... */ };
const req = httpGet(host, path, handleChunk);