【问题标题】:How to handle a redirect response with authentication in node.js?如何在 node.js 中处理带有身份验证的重定向响应?
【发布时间】:2011-12-13 17:49:32
【问题描述】:

出于学习目的,我没有使用外部模块,因此我正在尝试向服务器发出身份验证请求。它适用于 curl :

curl -L -u user:password http://webpage/email

[已解决,thansk ... ]但是在 node.js 中我有问题,这是我的代码:

var http = require("http");
var options = {
  hostname : 'webpage',
  port : '80',
  path : '/email',
  method : 'GET',
  headers : {
       "Connection" : "keep-alive",
       "User-Agent" : "Mozilla/5.0 (X11; Linux x86_64)"
  },
  auth : "username:password"
}

options.agent = new http.Agent(options);

var req = http.request(options, function(res) {
 // The authentication works fine, like curl without -L parameter
 // STATUS 302
 res.setEncoding('utf8');
 res.on('data',function(chunk){
  console.log(chunk);

 // SOLVED ! 

  var opts = {
   host : 'webpage',
   port : '80',
   path : '/email/',
   location : res.headers.location,
   auth : "user:password"
 }

 var require = http.request(opts,function(resp){
  resp.setEnconding("utf8");
  resp.on('data',function(chk){
   console.log(chk);
  });
 });

 require.end();
 // --------------

  // I got the same without -L parameter in curl
  // <head><title>Document Moved</title></head>
  // <body><h1>Object Moved</h1>This document may be found <a href="http://webpage/email/">here</a></body> <-- The 'Location' is the same

 });
});

req.on('error',function(e){
 console.log('Problem with request : ' + e.message);
}

req.end()

我尝试在标题中使用“位置”再次请求,但得到了相同的结果。

感谢您的帮助。

【问题讨论】:

  • 我知道你说你已经解决了这个问题,但它仍然值得其他人回答。

标签: javascript http node.js


【解决方案1】:

curl 中的 -u 允许您传递 Authentication 标头的值。在节点中,您将手动执行此操作。基本身份验证规范(我假设您正在使用)说以 base 64 编码格式传递凭据。在节点中手动执行此操作看起来像这样。

headers = {
  'Authorization': 'Basic ' + (new Buffer(user + ':' + pass)).toString('base64')
}

【讨论】:

  • 我认为标头的名称是“授权”,当我使用节点 v.0.4.7(对于 heroku)执行此请求时,由于 auth 属性不存在而出现错误在那个版本中,所以我尝试使用“授权”标题并且工作正常。
猜你喜欢
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-19
  • 1970-01-01
  • 2021-10-28
  • 1970-01-01
相关资源
最近更新 更多