我正在尝试使用polka js实现受保护的路由。我尝试使用中间件来实现它,但是即使对于不受保护的路由,我也一直遭到未经授权的访问。
const polka = require('polka');
const send = require('@polka/send-type');
const app = polka();
app.get('/un-protected', (req, res) => {
return send(res, 200, {
msg: 'Unprotected route',
});
});
const auth = false;
app
.use((req, res, next) => {
if (auth) {
next();
} else {
return send(res, 401, {
errors: {
msg: 'unauthorized',
},
});
}
})
.get('/protected', (req, res) => {
return send(res, 200, {
msg: 'Protected route',
});
});
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
预期的行为是,只有'/ protected'路由应该显示未经授权的消息,但是当前甚至对于'/ unprotected'路由仍会弹出未经授权的消息。
答案 0 :(得分:0)
在转到受保护的路由时,应将认证检查放在指定的路由和操作之间。
app.get('/un-protected', (req, res) => {
return send(res, 200, {
msg: 'Unprotected route',
});
});
const auth = false;
const checkAuth = (req, res, next) => {
if (auth) {
next();
} else {
return send(res, 401, {
errors: {
msg: 'unauthorized',
},
});
}
}
app
.get('/protected', checkAuth, (req, res) => {
return send(res, 200, {
msg: 'Protected route',
});
});