【问题标题】:Curl JSON Post with node-libcurl使用 node-libcurl 卷曲 JSON 帖子
【发布时间】:2019-08-11 07:49:07
【问题描述】:

我正在使用 node-libcurl 将 JSON 发布到 URL 并接收回 JSON。

我在 PHP 上测试了 CURL,它运行良好。

PHP代码如下

$data = array('user' => $us, 'pwd' => $cl);
$data_string = json_encode($data);

$ch = curl_init('http://52.234.214.55:9001/autenticacion/externo');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string))
);

$result = curl_exec($ch);

现在我想让它在如下所示的节点路由上工作:

app.post('/login2',function(req,res){

  //formato JSON ACHS
  var cvalue = {
      'user': 'user',
      'pwd': 'pass'
    }

    var curl = new Curl();

    curl.setOpt('URL', 'http://52.234.214.55:9001/autenticacion/externo');
    curl.setOpt('CURLOPT_CUSTOMREQUEST', "POST");
    curl.setOpt('CURLOPT_POSTFIELDS', cvalue);
    curl.setOpt('CURLOPT_RETURNTRANSFER', true);
    curl.setOpt('CURLOPT_HTTPHEADER', array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen(cvalue)));

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

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

    this.close();
});

curl.on('error', curl.close.bind(curl));
curl.perform();

})

这不起作用,我收到以下错误:

给出了未知的选项。第一个参数必须是选项内部 id 或选项名称。您可以使用 Curl.option 常量。 在 Curl.setOpt (C:\Users\Ingolf\workspace\w2_achs2\node_modules\node-libcurl\lib\Curl.js:980:11) 在 C:\Users\Ingolf\workspace\w2_achs2\index.js:130:10

这指向

curl.setOpt('CURLOPT_CUSTOMREQUEST', "POST");

按照文档中的建议和发现,我将其更改为:

curl.setOpt(Curl.option.URL, 'http://52.234.214.55:9001/autenticacion/externo');
curl.setOpt(Curl.option.CUSTOMREQUEST, "POST");
curl.setOpt(Curl.option.CURLOPT_POSTFIELDS, cvalue);
curl.setOpt(Curl.option.CURLOPT_RETURNTRANSFER, true);
curl.setOpt(Curl.option.CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen(cvalue)));

这会得到错误:

给出了未知的选项。第一个参数必须是选项内部 id 或选项名称。您可以使用 Curl.option 常量。 在 Curl.setOpt (C:\Users\Ingolf\workspace\w2_achs2\node_modules\node-libcurl\lib\Curl.js:980:11) 在 C:\Users\Ingolf\workspace\w2_achs2\index.js:131:10

指向

curl.setOpt(Curl.option.CURLOPT_POSTFIELDS, cvalue);

感谢您的帮助。

【问题讨论】:

    标签: node.js json curl


    【解决方案1】:

    查看node-libcurl 文档: https://github.com/JCMais/node-libcurl/blob/HEAD/api.md#curloption--enum

    更具体地说,您需要使用枚举选项而不是 cURL 兼容选项字符串:

    CURLOPT_URL 变成 Curl.option.URL

    试试这个:

    curl.setOpt(Curl.option.CUSTOMREQUEST, "POST");
    
    

    【讨论】:

      猜你喜欢
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-22
      相关资源
      最近更新 更多