2011-09-21 64 views
12

我想要做的是在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 - 

建议表示赞赏。

回答

9

使用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" } 
    } 
    } 
}); 
12

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

虽然没有对具体的卷曲绑定的NodeJS,我们仍然可以通过发出命令行界面卷曲的请求。 NodeJS带有child_process模块​​,它很容易让我们启动进程并读取它们的输出。这样做是相当直接的。我们只需要从child_process模块​​导入exec方法并调用它。第一个参数是我们想要执行的命令,第二个参数是一个接受错误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); 
} 

}); 

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

+0

为什么在命令行中使用卷曲时,你可以用'http.request'或Node.js的直接 – Raynos

+3

这只是另一种选择。他要求卷曲,所以我给他卷曲:) – mrryanjohnston

+3

CURL有比http.request更多的选择(包括代理支持) –