【发布时间】:2021-07-30 04:02:46
【问题描述】:
我正在尝试使用 Express JS 对用户名和密码进行基本身份验证。我面临的问题是,我想在 app.use() 函数中使用 if 语句,但它似乎没有返回任何内容。在下面找到代码sn-p,输出得到了
const express = require('express');
const app = express();
const basicAuth = require('express-basic-auth');
app.get('/protected', (req,res)=>{
app.use(basicAuth({authorizer: myAuthorizer}))
function myAuthorizer(username, password){
const userMatches = basicAuth.safeCompare(username, 'admin')
const passwordMatches = basicAuth.safeCompare(password, 'admin')
if(userMatches == 'admin' && passwordMatches == 'admin'){
res.send("Welcome, authenticated client");
}else{
res.send("401 Not authorized");
}
}});
app.listen(8080, ()=> console.log('Web Server Running on port 8080!'));
【问题讨论】:
标签: javascript express curl localhost