【问题标题】:cURL call to API in NodeJS Request在 NodeJS 请求中对 API 的 cURL 调用
【发布时间】:2016-07-02 16:04:12
【问题描述】:

又是我一个蹩脚的问题。我对正常工作的 Rattic 密码数据库 API 进行了以下调用:

curl -s -H 'Authorization: ApiKey myUser:verySecretAPIKey' -H 'Accept: text/json' https://example.com/passdb/api/v1/cred/\?format\=json

我试图在 NodeJS 中复制这个调用,但是以下返回空白:

var request = require('request');

url='https://example.com/passdb/api/v1/cred/?format=json';

request({
    url: url,
    method: 'POST',
    headers: [
        { 'Authorization': 'ApiKey myUser:verySecretAPIKey' }
    ],
    },
    function (error, response, body) {
        if (error) throw error;
        console.log(body);
    }
);

感谢任何帮助。

【问题讨论】:

  • 你试过GET吗?
  • 是的,body 变量仍然是空行(不是 null 或未定义):/

标签: node.js curl


【解决方案1】:
  • 正如 cmets 中已经指出的,使用 GET,而不是 POST
  • headers 应该是一个对象,而不是一个数组;
  • 您没有添加 Accept 标头。

所有组合,试试这个:

request({
  url     : url,
  method  : 'GET',
  headers : {
    Authorization : 'ApiKey myUser:verySecretAPIKey',
    Accept        : 'text/json'
  }, function (error, response, body) {
    if (error) throw error;
    console.log(body);
  }
});

【讨论】:

  • 我的 curl 请求包含数据 -d phonenumber=07XXXXXXX 如何将其添加到请求中
  • @IzzoObella 使用 body 选项
【解决方案2】:

标题应该是一个对象。

var request = require('request');

url='https://example.com/passdb/api/v1/cred/?format=json';

request({
            url: url,
            method: 'POST',
            headers: {
               'Authorization': 'ApiKey myUser:verySecretAPIKey' 
            }
        }, function (error, response, body) {
            if (error) throw error;
            console.log(body);
        });

【讨论】:

    【解决方案3】:

    您可以做的一件事是将 curl 请求导入 Postman,然后将其导出为不同的形式。比如nodejs:

    var http = require("https");
    
    var options = {
      "method": "GET",
      "hostname": "example.com",
      "port": null,
      "path": "/passdb/api/v1/cred/%5C?format%5C=json",
      "headers": {
        "authorization": "ApiKey myUser:verySecretAPIKey",
        "accept": "text/json",
        "cache-control": "no-cache",
        "postman-token": "c3c32eb5-ac9e-a847-aa23-91b2cbe771c9"
      }
    };
    
    var req = http.request(options, function (res) {
      var chunks = [];
    
      res.on("data", function (chunk) {
        chunks.push(chunk);
      });
    
      res.on("end", function () {
        var body = Buffer.concat(chunks);
        console.log(body.toString());
      });
    });
    
    req.end();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-11
      • 2015-01-20
      • 2018-04-16
      • 2021-01-07
      相关资源
      最近更新 更多