0

for learning purposes I'm not using external modules, so I'm trying to do an authentication request to a server. It works with curl :

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

[SOLVED, thansk ... ]But in node.js I have problems , this is my code :

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

I tried to request again with 'Location' in header, but I got the same result.

Thanks for your help.

1
  • I know you said you solved this already, but it still deserves an answer for others. Commented Dec 11, 2011 at 6:36

1 Answer 1

1

The -u in curl allows you to pass the value for the Authentication header. In node, you would do this manually. The spec for Basic Authentication (which I assume you're using) says pass the credentials in base 64 encoded format. Doing this manually in node looks something like this.

headers = {
  'Authorization': 'Basic ' + (new Buffer(user + ':' + pass)).toString('base64')
}
Sign up to request clarification or add additional context in comments.

1 Comment

I think so that the name of the header is "Authorization", when I did this request with node v.0.4.7 (for heroku), I got errors because the auth property doesn't exists in that version so I tried with "Authorization" header and works fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.