如何将Node.js后端的JSON数据(is_officer)传递到前端HTML
解决Node.js登录接口传递is_officer数据到前端页面的方案
下面提供三种实用的实现方式,你可以根据业务场景选择:
方案一:使用模板引擎(推荐,适合服务器端渲染场景)
通过模板引擎直接将数据注入HTML页面,无需前端额外请求。这里以EJS为例:
Node.js端代码
const express = require('express'); const app = express(); const axios = require('axios'); // 配置EJS模板引擎 app.set('view engine', 'ejs'); app.set('views', './views'); // 模板文件存放目录 // 解析POST请求体 app.use(express.urlencoded({ extended: true })); app.use(express.json()); app.post('/login', async (req, res) => { try { // 调用第三方认证接口 const authRes = await axios.post('第三方认证接口地址', { username: req.body.username, password: req.body.password }); const is_officer = authRes.data.is_officer; // 渲染模板并传递数据 res.render('timesheets', { is_officer }); } catch (err) { res.status(500).send('认证失败'); } }); app.listen(3000, () => console.log('服务器运行在3000端口'));
前端模板文件(./views/timesheets.ejs)
<!DOCTYPE html> <html> <head> <title>工时表</title> </head> <body> <script> // 直接从模板变量获取数据 const isOfficer = <%= JSON.stringify(is_officer) %>; console.log('用户身份:', isOfficer ? '职员' : '普通用户'); // 根据身份渲染不同内容 if (isOfficer) { document.body.innerHTML += '<h2>职员专属功能已启用</h2>'; } else { document.body.innerHTML += '<h2>欢迎使用普通用户功能</h2>'; } </script> </body> </html>
方案二:通过URL查询参数传递(实现简单,适合非敏感数据)
登录后重定向到页面并携带参数,前端从URL解析数据:
Node.js端代码
const express = require('express'); const app = express(); const axios = require('axios'); app.use(express.urlencoded({ extended: true })); app.use(express.json()); app.post('/login', async (req, res) => { try { const authRes = await axios.post('第三方认证接口地址', req.body); const is_officer = authRes.data.is_officer; // 重定向到页面并携带查询参数 res.redirect(`/timesheets?is_officer=${is_officer}`); } catch (err) { res.status(500).send('认证失败'); } }); // 提供timesheets页面的GET路由 app.get('/timesheets', (req, res) => { res.sendFile(__dirname + '/timesheets.html'); }); app.listen(3000);
前端HTML文件(timesheets.html)
<!DOCTYPE html> <html> <head> <title>工时表</title> </head> <body> <script> // 解析URL查询参数 const urlParams = new URLSearchParams(window.location.search); const isOfficer = urlParams.get('is_officer') === 'true'; // 注意类型转换 console.log('用户身份:', isOfficer ? '职员' : '普通用户'); // 后续业务逻辑使用isOfficer变量 </script> </body> </html>
方案三:通过Cookie传递(适合需要跨页面保持数据的场景)
登录后设置Cookie,前端读取Cookie获取数据:
Node.js端代码
const express = require('express'); const app = express(); const axios = require('axios'); app.use(express.urlencoded({ extended: true })); app.use(express.json()); app.post('/login', async (req, res) => { try { const authRes = await axios.post('第三方认证接口地址', req.body); const is_officer = authRes.data.is_officer; // 设置Cookie,httpOnly设为false允许前端读取(若无需前端读取可设为true提升安全性) res.cookie('is_officer', is_officer, { httpOnly: false, maxAge: 24 * 60 * 60 * 1000 // 有效期1天 }); // 返回页面 res.sendFile(__dirname + '/timesheets.html'); } catch (err) { res.status(500).send('认证失败'); } }); app.listen(3000);
前端HTML文件(timesheets.html)
<!DOCTYPE html> <html> <head> <title>工时表</title> </head> <body> <script> // 封装读取Cookie的函数 function getCookie(name) { const value = `; ${document.cookie}`; const parts = value.split(`; ${name}=`); if (parts.length === 2) return parts.pop().split(';').shift(); } const isOfficer = getCookie('is_officer') === 'true'; console.log('用户身份:', isOfficer ? '职员' : '普通用户'); // 业务逻辑代码 </script> </body> </html>
内容的提问来源于stack exchange,提问作者Pavan Bellamkonda
相关产品推荐
相关产品推荐

