【问题标题】:how to do this curl operation in node.js如何在 node.js 中执行此 curl 操作
【发布时间】:2011-11-21 20:31:53
【问题描述】:

我想做的是node.js中的这个curl操作。

curl -XPOST localhost:12060/repository/schema/fieldType -H 'Content-Type: application/json' -d '
{
  action: "create",
  fieldType: {
    name: "n$name",
    valueType: { primitive: "STRING" },
    scope: "versioned",
    namespaces: { "my.demo": "n" }
  }
}' -D -

欢迎提出建议。

【问题讨论】:

    标签: javascript node.js asynchronous


    【解决方案1】:

    通过这里http://query7.com/nodejs-curl-tutorial

    虽然没有针对 cURL 的特定 NodeJS 绑定,但我们仍然可以通过命令行界面发出 cURL 请求。 NodeJS 带有 child_process 模块,它允许我们轻松地启动进程并读取它们的输出。这样做是相当直接的。我们只需要从 child_process 模块中导入 exec 方法并调用它。第一个参数是我们要执行的命令,第二个是一个回调函数,接受error、stdout、stderr。

    var util = require('util');
    var exec = require('child_process').exec;
    
    var command = 'curl -sL -w "%{http_code} %{time_total}\\n" "http://query7.com" -o /dev/null'
    
    child = exec(command, function(error, stdout, stderr){
    
    console.log('stdout: ' + stdout);
    console.log('stderr: ' + stderr);
    
    if(error !== null)
    {
        console.log('exec error: ' + error);
    }
    
    });
    

    EDIT这也是一个可能的解决方案:https://github.com/dhruvbird/http-sync

    【讨论】:

    • 当你可以直接使用http.request或node.js时,为什么要从命令行使用curl
    • 这只是另一种选择。他要卷曲,所以我给了他卷曲:)
    • CURL 比 http.request 有更多的选项(包括代理支持)
    • 在某些代理配置中,当 curl 正常工作时,尝试让节点正确协商代理是令人抓狂的。对于有特定需求的人来说,这是一个不错的解决方法。
    • 如果您想处理 curl 返回的结果,也请参阅此答案,以便将侦听器附加到子进程。 stackoverflow.com/questions/14332721/…
    【解决方案2】:

    使用request。 request 是从 node.js 发出 HTTP 请求的事实上的标准方式。这是在http.request 之上的一个薄抽象

    request({
      uri: "localhost:12060/repository/schema/fieldType",
      method: "POST",
      json: {
        action: "create",
        fieldType: {
          name: "n$name",
          valueType: { primitive: "STRING" },
          scope: "versioned",
          namespaces: { "my.demo": "n" }
        }
      }
    });
    

    【讨论】:

      【解决方案3】:
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-29
      • 2010-10-03
      • 2011-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多