首页 > 解决方案 > 在节点 js 路由中使用外部函数

问题描述

我试图在我的路由中使用一个外部函数,它将更改应用于我的 ejs 视图。

这是我的项目的结构:

Project
    functions
        Evening.js
        Morning.js
        MyFunc.js
    routes
        about.js
        index.js
        users.js
    views
        about.ejs
        index.ejs
    app.js

另外我有我的 MyFunc.js:

var morning = require('./Morning');
var evening = require('./Evening');

module.exports = {
  GetMorningMessage: function () { console.log(morning); },
  GetEveningMessage: function () { console.log(evening); }
};

我知道我可以app.get()在我的 app.js 中使用来设置所有需要的参数以将某些更改应用于我的视图,但我想知道我是否可以app.use()在 app.js 中使用并在我的路由中调用外部函数,例如router.get()

例如像这样(在 index.js 中)

var morning = welcome.GetMorningMessage();

router.get('/', function (req, res) {
  res.render('index', {
    title: 'The index page!',
    h1: 'The h1',
    username: username,
    currentDate: currentDate,
    MyVar: morning
  });
});

标签: javascriptnode.jsvisual-studioexpressejs

解决方案


推荐阅读