Joã*_*imo 29 authentication restful-authentication http basic-authentication node.js
这是我要做一个简单的GET请求的代码:
var options = {
host: 'localhost',
port: 8000,
path: '/restricted'
};
request = http.get(options, function(res){
var body = "";
res.on('data', function(data) {
body += data;
});
res.on('end', function() {
console.log(body);
})
res.on('error', function(e) {
console.log("Got error: " + e.message);
});
});
Run Code Online (Sandbox Code Playgroud)
但是该路径"/ restricted"需要简单的基本HTTP身份验证.如何添加凭据进行身份验证?我在NodeJS手册中找不到与基本http认证相关的任何内容.提前致谢.
小智 50
您需要将Authorization添加到选项中,例如使用base64编码的标头.喜欢:
var options = {
host: 'localhost',
port: 8000,
path: '/restricted',
headers: {
'Authorization': 'Basic ' + new Buffer(uname + ':' + pword).toString('base64')
}
};
Run Code Online (Sandbox Code Playgroud)
tom*_*ekK 22
在较新的版本中,您还可以在选项中添加auth参数(格式为username:password,no encoding):
var options = {
host: 'localhost',
port: 8000,
path: '/restricted',
auth: username + ':' + password
};
request = http.get(options, function(res){
//...
});
Run Code Online (Sandbox Code Playgroud)
(注意:在v0.10.3上测试)