简体   繁体   中英

cURL call to API in NodeJS Request

it's me again with another lame question. I have the following call to a Rattic password database API which works properly:

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

I tried to replicate this call in NodeJS, however the following returns blank:

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

Any help is appreciated.

  • As pointed out in the comments already, use GET , not POST ;
  • headers should be an object, not an array;
  • You're not adding the Accept header.

All combined, try this:

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

Headers should be an object.

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

One thing you can do is import a curl request into Postman and then export it into different forms. for example, 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM