在 Node.js 中等效的 cURL?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6819143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:24:17  来源:igfitidea点击:

cURL equivalent in Node.js?

curlnode.js

提问by slifty

I'm looking to use information from an HTTP request using Node.js (i.e. call a remote web service and echo the response to the client).

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

In PHP I would have used cURL to do this. What is the best practice in Node?

在 PHP 中,我会使用 cURL 来做到这一点。Node 中的最佳实践是什么?

采纳答案by Dan Grossman

See the documentation for the HTTP module for a full example:

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

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

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

回答by Facebook Staff are Complicit

The httpmodule that you use to run servers is also used to make remote requests.

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

Here's the example in their docs:

这是他们文档中的示例:

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();

回答by Nitish Agarwal

you can easily use request module:

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

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

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

Sample code:

示例代码:

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

回答by JCM

Since looks like node-curlis dead, I've forked it, renamed, and modified to be more curl like and to compile under Windows.

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

node-libcurl

node-libcurl

Usage example:

用法示例:

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();

Perform is async, and there is no way to use it synchronous currently (and probably will never have).

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

It's still in alpha, but this is going to change soon, and help is appreciated.

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

Now it's possible to use Easyhandle directly for sync requests, example:

现在可以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 ) );

Also, the project is stable now!

此外,该项目现已稳定!

回答by Aronis Mariano

EDIT:

编辑:

For new projects please refrain from using request, since now the project is in maitainance mode, and will eventually be deprecated

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

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

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

Instead i would recommend Axios, the library is in line with Node latest standards, and there are some available plugins to enhance it, enabling mock server responses, automatic retries and other features.

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

https://github.com/axios/axios

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

Or using async / await:

或者使用异步/等待:

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


I usually use REQUEST, its a simplified but powerful HTTP client for Node.js

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

https://github.com/request/request

https://github.com/request/request

Its on NPM npm install request

它在 NPM npm install request

Here is a usage sample:

这是一个使用示例:

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

回答by warfares

well if you really need a curl equivalent you can try node-curl

好吧,如果你真的需要一个 curl 等价物,你可以尝试 node-curl

npm install node-curl

you will probably need to add libcurl4-gnutls-dev.

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

回答by Brad Dickason

The above examples work but don't go so far as to really deal with a real world example (i.e. when you process data coming in multiple chunks. One thing you need to make sure of is that you have an 'on chunk' handler that push's the data into an array (fastest way to do this in JS) and an 'on end' handler that joins them all together so you can return it.

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

This is especially necessary when you're working with big requests (5000+ lines) and the server sends a bunch of data at you.

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

Here's an example in one of my programs (coffeescript): https://gist.github.com/1105888

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

回答by Laksh Goel

There is npm module to make a curl like request, npm curlrequest.

有 npm 模块可以制作类似请求的卷曲,npm curlrequest.

Step 1: $npm i -S curlrequest

第1步: $npm i -S curlrequest

Step 2: In your node file

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

For further reading and understanding, npm curlrequest

为了进一步阅读和理解,npm curlrequest

回答by D M Patel

Use request npm module and after call

使用请求 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.
});

For best practice also use some winstonlogger module or else simple console.log and then run your application like

对于最佳实践,还可以使用一些winston记录器模块或其他简单的 console.log,然后运行您的应用程序,例如

npm start output.txt 

Result of above command will generate one txt file on root with all data which you have printed in console.log

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