1

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.

2
  • 1
    Have you tried with GET? Commented Jul 2, 2016 at 16:07
  • Yup, body variable is still an empty line (not null or undefined) :/ Commented Jul 2, 2016 at 16:10

3 Answers 3

2
  • 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);
  }
});
Sign up to request clarification or add additional context in comments.

2 Comments

My curl request contains data -d phonenumber=07XXXXXXX how can i add that to the request
@IzzoObella using the body option
2

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.