cURL调用NodeJS Request中的API

时间:2016-07-02 16:04:12

标签: node.js curl

再次提出另一个蹩脚的问题。我有以下调用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);
    }
);

感谢任何帮助。

3 个答案:

答案 0 :(得分:2)

  • 正如评论中已经指出的那样,使用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);
  }
});

答案 1 :(得分:1)

标题应该是一个对象。

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);
        });

答案 2 :(得分:1)

您可以做的一件事是将一个卷曲请求导入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();