如何在 node.js 客户端中进行身份验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15986204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:12:27  来源:igfitidea点击:

how to do Auth in node.js client

node.jsbasic-authenticationnode.js-client

提问by Sau

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

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

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

回答by Noah

The requestmodule will make your life easier. It now includes a Basic Authas 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

安装请求执行 npm install -S request

回答by hypervillain

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."

在您的评论中,您会问:“我在命令提示符中获得的 JSOn 是否可以通过 javascript 或 Jquery 或任何方式进入 UI。”

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