javascript 在 Mocha 和 SuperTest 中设置 Basic Auth
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28756543/
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
Setting Basic Auth in Mocha and SuperTest
提问by Peter Chappy
I'm trying to set us a test to verify the username and password of a path blocked by the basic auth of a username and password.
我正在尝试为我们设置一个测试,以验证被用户名和密码的基本身份验证阻止的路径的用户名和密码。
it('should receive a status code of 200 with login', function(done) {
request(url)
.get("/staging")
.expect(200)
.set('Authorization', 'Basic username:password')
.end(function(err, res) {
if (err) {
throw err;
}
done();
});
});
回答by Yves M.
Using the auth method
使用 auth 方法
SuperTestis based on SuperAgentwhich provides the authmethod to facilitate Basic Authentication:
SuperTest基于SuperAgent,它提供了auth方法来促进基本身份验证:
it('should receive a status code of 200 with login', function(done) {
request(url)
.get('/staging')
.auth('the-username', 'the-password')
.expect(200, done);
});
Source: http://visionmedia.github.io/superagent/#basic-authentication
来源:http: //visionmedia.github.io/superagent/#basic-authentication
PS: You can pass done
straight to any of the .expect()
calls
PS:您可以done
直接传递给任何.expect()
调用
回答by pretorh
The username:password
part must be base64 encoded
该username:password
部分必须是 base64 编码的
You can use something like
你可以使用类似的东西
.set("Authorization", "basic " + new Buffer("username:password").toString("base64"))