Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

npm request with headers and auth

Tags:

node.js

curl

I am trying to access an API using "request" npm. This API requires header "content-type" and a basic authentication. here is what I've done so far.

var request = require('request');
var options = {
  url: 'https://XXX/index.php?/api/V2/get_case/2',
  headers: {
    'content-type': 'application/json'
  },

};
request.get(options, function(error, response, body){
console.log(body);
}

).auth("[email protected]","password",false);

upon executing this using Node , I am getting an error that says invalid username and password. I've validated the same API, authentication and header using CURL with the command below and it gave an expected HTTP response.

curl -X GET -H "content-type: application/json" -u [email protected]:password "https://XXX/index.php?/api/V2/get_case/2"

Please suggest the right way to code request with auth and header.


Here is my update code

var auth = new Buffer("[email protected]" + ':' + "password").toString('base64');
     var req = {
                    host: 'https://URL',
                    path: 'index.php?/api/v2/get_case/2',
                    method: 'GET',
                    headers: {
                        Authorization: 'Basic ' + auth,
                        'Content-Type': 'application/json'
                              }
                };
    request(req,callback);
    function callback(error, response, body) {
      console.log(body);
    }

I am seeing 'undefined' in my console. can you help me here?

like image 397
Praveen Kumar Avatar asked May 09 '15 07:05

Praveen Kumar


2 Answers

Here is how it worked for me

 var auth = new Buffer(user + ':' + pass).toString('base64');
 var req = {
     host: 'https://XXX/index.php?/api/V2/get_case/2',
     path: path,
     method: 'GET',
     headers: {
         Authorization: 'Basic ' + auth,
         'Content-Type': 'application/json'
     }
 };
like image 59
Katya Pavlenko Avatar answered Nov 10 '22 15:11

Katya Pavlenko


request(url, {
  method: "POST",
  auth: {
    user: this.user,
    pass: this.pass
  }
}, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      console.log('body:', body);
    } else {
      console.log('error', error, response && response.statusCode);
    }
});
like image 26
Ray Hulha Avatar answered Nov 10 '22 15:11

Ray Hulha