如何做验证在客户端的Node.js(how to do Auth in node.js client

2019-08-22 16:45发布

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

Answer 1:

该请求模块将使您的生活更轻松。 现在包括基本身份验证作为一个选项,这样你就不必建立自己的头。

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

要安装请求执行npm install -S request



Answer 2:

在您的评论你问,“有什么办法,我得到的命令提示符下JSON会在无论是JavaScript或的jQuery或通过任何手段的用户界面。”

嘿,只是身体返回到客户端:

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


文章来源: how to do Auth in node.js client