I use node js and express js. I want to make sure that if app.get is without a token parameter, then upload an html file with js that will pass the token. And if the token was passed, then show another html file.
But I do not know how to make a redirect from the client with the transfer of a header with a token
Server:
app.get("/admin-cp/:page", function (req, res) {
const idToken = req.headers.authorization;
if (!idToken)
{
res.sendFile(path.join(initial_path, "admin-cp/loader.html"));
//return res.status(401).send("Unauthorized")
}
const sessionCookie = req.cookies.session || "";
admin
.auth()
.verifySessionCookie(sessionCookie, true )
.then((userData) => {
console.log("Logged in:", userData.email)
console.log('Авторизован. Доступ в админ панель открыт')
admin
.auth()
.verifyIdToken(idToken)
.then((claims) =>
{
if (claims.admin === true)
{
console.log('Зашёл с правами администратора', req.params.page);
if (req.params.page === 'analytics')
{
console.log("Open analytics");
res.sendFile(path.join(initial_path, "admin-cp/main-admin_cp.html"));
//res.render(path.join(initial_path, "admin-cp/main-admin_cp.html"));
//res.redirect('/admin-cp/home');
}
}
else if (claims.admin === false)
{
console.log('Зашёл без прав администратора');
//res.sendFile(path.join(initial_path, "admin-cp/global_not_permission.html"));
res.redirect('/');
}
});
})
.catch((error) => {
console.log('Не авторизован. Ошибка', error, ' отсутвует userData')
res.redirect("/login");
});
});
I tried to do with “fetch”:
const res = await fetch('/admin-cp/analytics', { headers: { authorization: idToken }, redirect: 'follow' })
.then(res => {
console.log(res);
if (res.redirected) {
document.location = res.url;
}
})
But this led to an error:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client