如何在node.js客户端中进行身份验证 [英] how to do Auth in node.js client

查看:109
本文介绍了如何在node.js客户端中进行身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过身份验证使用此rest api.我正在尝试包括标头,但没有得到任何回应.它抛出的输出通常是在没有身份验证时抛出的.谁能建议我一些解决方案.下面是我的代码

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

推荐答案

请求模块将使您生活更轻松.现在,它包含一个基本身份验证作为选项,因此您无需自己构建Header

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

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

这篇关于如何在node.js客户端中进行身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆