账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    express 怎么给所有要 render 的页面赋值一个变量?
    53
    0

    目前我的使用方法是

    const express = require('express');
    const Router = express.Router();
    const path = require('path');
    const src = path.resolve(__dirname, '../src/');
    // 自动路由
    const fs = require('fs'),
        PathRouter = [];
    // 同步读取文件
    fs.readdirSync(`${src}/views`).forEach(file => {
        if (file.indexOf('.html') > -1) {
            PathRouter.push(file.substr(0, file.indexOf('.html')));
        }
    })
    
    PathRouter.forEach(function(item) {
        Router.get(`/${item}`, function(req, res) {
            let {deviceId} = req.cookies;
            if (item === 'index') {
                return res.redirect('/'); // 重定向到 / 
            }
            res.render(`${item}.html`, {deviceId}); // 这里在给所有要渲染的页面赋值一个变量
        });
    });
    
    
    module.exports = Router

    但是我现在改配置,改结构了,不用上面的方式了。

    我用的是这样的方式
    IndexController.js

    module.exports = function(app) {
        app.get('(\/|\/index)', function(req, res) {
            let { deviceId } = req.cookies;
            res.render('index.html', {
                deviceId
            });
        });
    }

    那么如果有 OtherController.js,我又要重新赋值一次了

    module.exports = function(app) {
        app.get('(\/|\/index)', function(req, res) {
            let { deviceId } = req.cookies;
            res.render('other.html', {
                deviceId
            });
        });
    }

    所以想知道 express 怎么给所有要 render 的页面赋值一个变量?

    2
    打赏
    收藏
    点击回答
        全部回答
    • 0
    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部