Javascript 如何在 node.js 中执行此 curl 操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7498648/
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-08-24 02:31:12  来源:igfitidea点击:

how to do this curl operation in node.js

javascriptnode.jsasynchronous

提问by XMen

What I would like to do is this curl operation in node.js.

我想做的是在node.js.

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 -

Suggestions are appreciated.

建议表示赞赏。

采纳答案by Raynos

Use request. request is the de-facto standard way to make HTTP requests from node.js. It's a thin abstraction on top of http.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" }
    }
  }
});

回答by mrryanjohnston

via here http://query7.com/nodejs-curl-tutorial

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

Although there are no specific NodeJS bindings for cURL, we can still issue cURL requests via the command line interface. NodeJS comes with the child_process module which easily allows us to start processes and read their output. Doing so is fairly straight forward. We just need to import the exec method from the child_process module and call it. The first parameter is the command we want to execute and the second is a callback function that accepts error, stdout, stderr.

尽管没有针对 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);
}

});

EDITThis is also a possible solution: https://github.com/dhruvbird/http-sync

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