【问题标题】:cURL equivalent in Node.js?Node.js 中的 cURL 等效项?
【发布时间】:2011-10-12 17:53:57
【问题描述】:

我希望通过 Node.js 使用来自 HTTP 请求的信息(即调用远程 Web 服务并将响应回显给客户端)。

在 PHP 中,我会使用 cURL 来执行此操作。 Node 的最佳实践是什么?

【问题讨论】:

  • http.request...
  • 所有这些解决方案的问题是它们需要控制cors!

标签: curl node.js


【解决方案1】:

有关完整示例,请参阅 HTTP 模块的文档:

https://nodejs.org/api/http.html#http_http_request_options_callback

【讨论】:

  • 另外值得指出的是有一个非常流行的包装库request.jsgithub.com/mikeal/request
  • http 请求是异步的,curl 是同步的。
  • @WHK 这就是 node.js 的本质
  • 本站可以将你的cURL命令转换成node.js请求:curl.trillworks.com/#node
  • 欢迎来到现实:request 已被弃用,见 github.com/request/request/issues/3142 在我看来 http.request 有更大的潜力
【解决方案2】:

用于运行服务器的http 模块也用于发出远程请求。

这是他们文档中的示例:

var http = require("http");

var options = {
  host: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST'
};

var req = http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

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

// write data to request body
req.write('data\n');
req.write('data\n');
req.end();

【讨论】:

  • 与 OP 要求的类似卷曲的行为相比,这是非常低的水平。
  • 致所有人:如今,请使用request - npmjs.com/package/request - 并在下面为 Nitish 的答案投票,这是 2018 年更好的答案。
  • 欢迎来到现实:request已被弃用,见github.com/request/request/issues/3142在我看来“低级”操作比这更有潜力,因为它一点也不低,它是BASIC
【解决方案3】:

您可以轻松使用请求模块:

https://www.npmjs.com/package/request

示例代码:

var request = require('request');
request('http://www.google.com', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body) // Show the HTML for the Google homepage. 
  }
  else {
    console.log("Error "+response.statusCode)
  }
})

【讨论】:

  • 只是一个笔记更新,'request' 现已弃用
【解决方案4】:

由于node-curl 看起来已经死了,我已经对其进行了分叉、重命名和修改,使其更像 curl 并在 Windows 下编译。

node-libcurl

使用示例:

var Curl = require( 'node-libcurl' ).Curl;

var curl = new Curl();

curl.setOpt( Curl.option.URL, 'www.google.com' );
curl.setOpt( 'FOLLOWLOCATION', true );

curl.on( 'end', function( statusCode, body, headers ) {

    console.info( statusCode );
    console.info( '---' );
    console.info( body.length );
    console.info( '---' );
    console.info( headers );
    console.info( '---' );
    console.info( this.getInfo( Curl.info.TOTAL_TIME ) );

    this.close();
});

curl.on( 'error', function( err, curlErrorCode ) {

    console.error( err.message );
    console.error( '---' );
    console.error( curlErrorCode );

    this.close();

});

curl.perform();

执行是异步的,目前没有办法同步使用它(可能永远不会有)。

它仍处于 alpha 阶段,但很快就会改变,非常感谢您的帮助。

现在可以直接使用Easy 句柄来处理同步请求,例如:

var Easy = require( 'node-libcurl' ).Easy,
    Curl = require( 'node-libcurl' ).Curl,
    url = process.argv[2] || 'http://www.google.com',
    ret, ch;

ch = new Easy();

ch.setOpt( Curl.option.URL, url );

ch.setOpt( Curl.option.HEADERFUNCTION, function( buf, size, nmemb ) {

    console.log( buf );

    return size * nmemb;
});

ch.setOpt( Curl.option.WRITEFUNCTION, function( buf, size, nmemb ) {

    console.log( arguments );

    return size * nmemb;
});

// this call is sync!
ret = ch.perform();

ch.close();

console.log( ret, ret == Curl.code.CURLE_OK, Easy.strError( ret ) );

另外,项目现在稳定了!

【讨论】:

  • 我尝试安装 node-curl 和 node-libcurl,但都给了我相同的消息:“找不到 curl 的头文件。”这是在node tools/retrieve-win-deps && node tools/generate-stubs && node-gyp rebuild 步骤期间。有什么想法吗?
  • @GreatBigBore 你需要在你的机器上安装 libcurl 开发包。例如,如果您使用的是 debian,则可以使用 $ apt-get install libcurl4-openssl-dev 安装它
  • 你能以某种方式使用-L 选项吗?
  • 是的:CURLOPT_FOLLOWLOCATION,你将使用 node-libcurl curl.setOpt( 'FOLLOWLOCATION', true );。顺便说一句,这样的问题比这个评论部分更适合issue tracker。 ;)
  • 由于node-pre-gypnode v15 的依赖性问题,我未能在Ubuntu 20_04 上安装node-libcurl。所以 lower node version 可以提供帮助,但 apt 依赖项呢?
【解决方案5】:

编辑:

对于新项目,请不要使用request,因为现在项目处于维护模式,最终将被弃用

https://github.com/request/request/issues/3142

我会推荐 Axios,该库符合 Node 最新标准,并且有一些可用的插件来增强它,支持模拟服务器响应、自动重试和其他功能。

https://github.com/axios/axios

const axios = require('axios');

// Make a request for a user with a given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });

或者使用异步/等待:

try{
    const response = await axios.get('/user?ID=12345');
    console.log(response)
} catch(axiosErr){
    console.log(axiosErr)
}

我通常使用 REQUEST,它是 Node.js 的一个简化但功能强大的 HTTP 客户端

https://github.com/request/request

在 NPM 上 npm install request

这是一个使用示例:

var request = require('request');

request('http://www.google.com', function (error, response, body) {
   if (!error && response.statusCode == 200) {
       console.log(body) // Show the HTML for the Google homepage.
   }
})

【讨论】:

    【解决方案6】:

    如果你真的需要 curl 等价物,你可以试试 node-curl

    npm install node-curl
    

    您可能需要添加libcurl4-gnutls-dev

    【讨论】:

      【解决方案7】:

      上述示例有效,但并没有真正处理现实世界的示例(即,当您处理来自多个块的数据时。您需要确保的一件事是您有一个'on chunk ' 将数据推送到数组中的处理程序(在 JS 中执行此操作的最快方式)和一个 'on end' 处理程序将它们全部连接在一起以便您可以返回它。

      当您处理大型请求(超过 5000 行)并且服务器向您发送大量数据时,这尤其必要。

      这是我的一个程序(coffeescript)中的一个示例: https://gist.github.com/1105888

      【讨论】:

        【解决方案8】:
        【解决方案9】:

        有一个 npm 模块可以发出类似 curl 的请求,npm curlrequest

        第一步:$npm i -S curlrequest

        第 2 步:在您的节点文件中

        let curl = require('curlrequest')
        let options = {} // url, method, data, timeout,data, etc can be passed as options 
        curl.request(options,(err,response)=>{
        // err is the error returned  from the api
        // response contains the data returned from the api
        })
        

        如需进一步阅读和理解,npm curlrequest

        【讨论】:

          【解决方案10】:

          使用 request npm 模块和调用后

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

          为了获得最佳实践,还可以使用一些 winston 记录器模块或简单的 console.log,然后像

          那样运行您的应用程序
          npm start output.txt 
          

          上述命令的结果将在 root 上生成一个 txt 文件,其中包含您在 console.log 中打印的所有数据

          【讨论】:

            【解决方案11】:

            使用reqclient,它是request 之上的一个小型客户端模块,允许您使用 cURL 样式记录所有活动(可选,用于开发环境)。还具有不错的功能,例如 URL 和参数解析、身份验证集成、缓存支持等。

            例如,如果您创建一个客户端对象并执行一个请求:

            var RequestClient = require("reqclient").RequestClient;
            var client = new RequestClient({
                    baseUrl:"http://baseurl.com/api/v1.1",
                    debugRequest:true, debugResponse:true
                });
            
            var resp = client.post("client/orders", {"client":1234,"ref_id":"A987"}, {headers: {"x-token":"AFF01XX"}})
            

            它将在控制台中记录如下:

            [Requesting client/orders]-> -X POST http://baseurl.com/api/v1.1/client/orders -d '{"client": 1234, "ref_id": "A987"}' -H '{"x-token": "AFF01XX"}' -H Content-Type:application/json
            [Response   client/orders]<- Status 200 - {"orderId": 1320934}
            

            请求会返回一个Promise对象,所以你必须用thencatch来处理结果。

            reqclient 可通过 npm 获得,您可以使用以下方式安装模块:npm install reqclient

            【讨论】:

              【解决方案12】:

              这是一个标准库 (http) async / await 解决方案。

              const http = require("http");
              
              const fetch = async (url) => {
                return new Promise((resolve, reject) => {
                  http
                    .get(url, (resp) => {
                      let data = "";
                      resp.on("data", (chunk) => {
                        data += chunk;
                      });
                      resp.on("end", () => {
                        resolve(data);
                      });
                    })
                    .on("error", (err) => {
                      reject(err);
                    });
                });
              };
              

              用法:

              await fetch("http://example.com");
              

              【讨论】:

                【解决方案13】:

                我最终使用了grunt-shell 库。

                Here 是我完全实现的 Grunt 任务的源代码,供其他考虑使用 EdgeCast API 的人使用。您会在我的示例中发现,我使用 grunt-shell 执行 curl 命令来清除 CDN。

                这是我花了几个小时试图让 HTTP 请求在 Node.js 中工作后得到的结果。我能够得到一个在 Ruby 和 Python 中工作的人,但不符合这个项目的要求。

                【讨论】:

                  【解决方案14】:

                  您可以尝试使用 POSTMAN Chrome 应用程序来处理您的请求,并且可以从那里生成节点 js 代码

                  【讨论】:

                    【解决方案15】:

                    我在从 IOT RaspberryPi 向云数据库发送 POST 数据时遇到问题,但几个小时后我设法解决了问题。

                    我使用命令提示符来执行此操作。

                    sudo curl --URL http://<username>.cloudant.com/<database_name> --user <api_key>:<pass_key> -X POST -H "Content-Type:application/json" --data '{"id":"123","type":"987"}'
                    

                    命令提示符将显示问题 - 用户名/密码错误;错误的请求等。

                    --URL 数据库/服务器位置(我使用了简单的免费 Cloudant DB) --user 是认证部分 username:pass 我是通过API pass输入的 -X 定义调用什么命令(PUT、GET、POST、DELETE) -H 内容类型 - Cloudant 是关于文档数据库,其中使用 JSON --data 内容本身按 JSON 排序

                    【讨论】:

                      【解决方案16】:

                      Request npm 模块Request node moulde 很好用,它有get/post请求的选项设置,而且在生产环境中也被广泛使用。

                      【讨论】:

                        【解决方案17】:

                        您可以使用请求 npm 模块。 使用超级简单。 请求被设计为进行 http 调用的最简单方法。它支持 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.
                        });
                        

                        【讨论】:

                          【解决方案18】:

                          您可能想尝试使用类似的东西

                          curl = require('node-curl');
                          curl('www.google.com', function(err) {
                            console.info(this.status);
                            console.info('-----');
                            console.info(this.body);
                            console.info('-----');
                            console.info(this.info('SIZE_DOWNLOAD'));
                          });
                          

                          【讨论】:

                            猜你喜欢
                            • 2018-10-31
                            • 1970-01-01
                            • 2014-07-01
                            • 2011-01-10
                            • 2010-09-12
                            • 1970-01-01
                            • 1970-01-01
                            • 2016-08-23
                            • 1970-01-01
                            相关资源
                            最近更新 更多