如何在node.js中处理带有身份验证的重定向响应

How to handle a redirect response with authentication in node.js?

本文关键字:身份验证 重定向 响应 处理 node js      更新时间:2023-09-26

学习目的我不使用外部模块,所以我试图做一个身份验证请求到服务器。它适用于curl:

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

[解决了,谢谢…]但是在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()

我试着在标题中再次请求"位置",但我得到了相同的结果。

谢谢你的帮助。

curl中的-u允许您传递Authentication头的值。在node中,您将手动执行此操作。基本身份验证(我假设您正在使用)的规范要求以base 64编码格式传递凭据。在node中手动执行此操作如下所示:

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