我有一个测试API。在此api中,我在解析后从“ curl -u username:password”获取用户名和密码。但是我不想解析每个api中的用户名和密码。我们可以通过任何方式做到这一点吗? 示例:
app.get('/test',function(req,res){
var header=req.headers['authorization']||'',
token=header.split(/\s+/).pop()||'', // and the encoded auth token
auth=new Buffer.from(token, 'base64').toString(), // convert from base64
parts=auth.split(/:/), // split on colon
username=parts[0],
password=parts[1];
"'+password+'"')
if(username=="username" && password=="password"){
res.status(200).json({
"data":"/v1/test"
});
}else
res.status(422).json({
"error":"Invalid Username Password"
});
});*
答案 0 :(得分:3)
您可以尝试表达中间件。
const checkUsernameAndPassword = (req, res, next) => {
var header=req.headers['authorization']||'',
token=header.split(/\s+/).pop()||'', // and the encoded auth token
auth=new Buffer.from(token, 'base64').toString(), // convert from base64
parts=auth.split(/:/), // split on colon
username=parts[0],
password=parts[1];
"'+password+'"')
if(username=="username" && password=="password"){
return next();
} else {
return res.status(422).json({
"error":"Invalid Username Password"
});
}
};
app.get('/test', checkUsernameAndPassword, function(req,res){
return res.status(200).json({ "data":"/v1/test" });
});