基于 NodeJS 的 HTTP 客户端:如何验证请求?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6918302/
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
HTTP Client based on NodeJS: How to authenticate a request?
提问by Jo?o Pinto Jerónimo
This is the code I have to make a simple GET request:
这是我必须发出简单 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);
});
});
But that path "/restricted" requires a simple basic HTTP authentication. How do I add the credentials to authenticate? I couldn't find anything related to basic http authentication in NodeJS' manual. Thanks in advance.
但是该路径“/restricted”需要一个简单的基本 HTTP 身份验证。如何添加凭据以进行身份验证?我在NodeJS 的手册中找不到与基本 http 身份验证相关的任何内容。提前致谢。
回答by Marcus Granstr?m
You need to add the Authorization to the options like a header encoded with base64. Like:
您需要将授权添加到选项中,例如使用 base64 编码的标头。喜欢:
var options = {
host: 'localhost',
port: 8000,
path: '/restricted',
headers: {
'Authorization': 'Basic ' + new Buffer(uname + ':' + pword).toString('base64')
}
};
回答by tomekK
In newer version you can also just add authparameter (in format username:password, no encoding) to your options:
在较新的版本中,您还可以将auth参数(格式为用户名:密码,无编码)添加到您的选项中:
var options = {
host: 'localhost',
port: 8000,
path: '/restricted',
auth: username + ':' + password
};
request = http.get(options, function(res){
//...
});
(NOTE: tested on v0.10.3)
(注意:在 v0.10.3 上测试过)
回答by gevorg
I suggest to use requestmodule for that, it support wide range functionalities including HTTP Basic Authentication.
我建议为此使用请求模块,它支持广泛的功能,包括 HTTP 基本身份验证。
var username = 'username',
password = 'password',
url = 'http://' + username + ':' + password + '@some.server.com';
request({url: url}, function (error, response, body) {
// Do more stuff with 'body' here
});

