登录成功后受保护页面HTML返回但不渲染、路由未更新的问题求助
登录成功后受保护页面HTML返回但不渲染、路由未更新的问题求助
大家好,我最近在做一个带Firebase认证的受保护页面功能,折腾了好一阵还是没搞定,来请教下各位!
我的需求很明确:用户登录成功后,要跳转到受保护的/admin/overview页面,并且正确渲染这个页面的HTML内容。
前端登录代码
我写了一个前端的登录函数,用Firebase的邮箱密码登录,拿到ID Token后,带着这个Token去请求受保护的后端接口:
async function getFirebaseAuthToken() { try { const email = this.email.value; const password = this.password.value; const userCredential = await auth.signInWithEmailAndPassword(email, password); const user = userCredential.user; // 获取Firebase ID Token const idToken = await user.getIdToken(true); // 请求受保护的后端接口 const response = await fetch('https://localhost:8000/admin/overview', { method: 'GET', headers: { 'Content-Type': 'application/json', 'Authorization': idToken }, }); } catch (error) { // 处理登录错误 console.error('Login error:', error.message); } }
后端认证中间件
后端我写了一个中间件来验证Token,通过的话才允许访问后续接口:
const authenticateUser = async (req, res, next) => { const { authorization } = req.headers; try { const decodedToken = await admin.auth().verifyIdToken(authorization); req.user = decodedToken; next(); } catch (error) { console.error('Error decoding token:', error); res.status(401).json({ error: 'Unauthorized' }); } };
后端受保护路由
如果中间件验证通过,就返回对应的HTML页面:
app.get('/admin/overview', authenticateUser, (req, res) => { const file_Path = path.join(__dirname, 'public/', 'admin.html'); res.setHeader('Content-Type', 'text/html'); res.sendFile(file_Path); });
遇到的问题
现在的情况是:网络面板里能看到请求成功返回了正确的HTML,预览也能看到HTML内容,但浏览器就是不渲染这个HTML!而且地址栏还停留在/admin/login,完全没有跳转到/admin/overview。
我也想过要把页面跳转和请求结合起来,比如同时用window.location.href = "https://localhost:8000/admin/overview"和fetch,但不知道怎么搭配才对,试了好多次都没效果。
有没有大佬能帮我看看哪里出问题了?为什么返回的HTML不渲染,路由也不更新呢?
备注:内容来源于stack exchange,提问作者Aalexander
相关产品推荐
相关产品推荐

