how to do Auth in node.js client

倖福魔咒の 提交于 2019-11-27 05:59:50

问题


I want to get use this rest api with authentication. I'm trying including header but not getting any response. it is throwing an output which it generally throw when there is no authentication. can anyone suggest me some solutions. below is my code

var http = require('http');

var optionsget = {
    host : 'localhost', // here only the domain name

    port : 1234,

    path:'/api/rest/xyz',
            headers: {
     'Authorization': 'Basic ' + new Buffer('abc'+ ':' + '1234').toString('base64')
   } ,
    method : 'GET' // do GET

};

console.info('Options prepared:');
console.info(optionsget);
console.info('Do the GET call');

var reqGet = http.request(optionsget, function(res) {
    console.log("statusCode: ", res.statusCode);

    res.on('data', function(d) {
        console.info('GET result:\n');
        process.stdout.write(d);
        console.info('\n\nCall completed');
    });

});

reqGet.end();
reqGet.on('error', function(e) {
    console.error(e);
});

回答1:


The request module will make your life easier. It now includes a Basic Auth as an option so you don't have build the Header yourself.

var request = require('request')
var username = 'fooUsername'
var password = 'fooPassword'
var options = {
  url: 'http://localhost:1234/api/res/xyz',
  auth: {
    user: username,
    password: password
  }
}

request(options, function (err, res, body) {
  if (err) {
    console.dir(err)
    return
  }
  console.dir('headers', res.headers)
  console.dir('status code', res.statusCode)
  console.dir(body)
})

To install request execute npm install -S request




回答2:


In your comment you ask, "Is there any way that the JSOn I'm getting in the command prompt will come in the UI either by javascript or by Jquery or by any means."

Hey, just return the body to your client:

exports.requestExample = function(req,res){
  request(options, function (err, resp, body) {
    if (err) {
      console.dir(err)
      return;
    }
    // parse method is optional
    return res.send(200, JSON.parse(body));
  });
};


来源:https://stackoverflow.com/questions/15986204/how-to-do-auth-in-node-js-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!