简体   繁体   English

从.use(req,res)更改为使用route.js文件时Express应用程序出错

[英]Error in express app when changing from .use(req,res) to using a routes.js file

I have a site in express and am trying to convert it to use a routes.js file to clean things up. 我有一个快递网站,正在尝试将其转换为使用route.js文件进行清理。 I am getting a TypeError, explained below. 我收到TypeError,如下所述。 I have read this and this but I still can't figure it out. 我已阅读这个这个 ,但我仍然无法弄清楚。 Currently the site works with the following lines: 当前,该站点使用以下行:

const server = express()
    .set('view engine', 'ejs') // set up ejs for templating
    .use(flash()) // use connect-flash for flash messages stored in session
  .use((req, res) => res.render('../views/pages/indextimewithall.ejs', {stockSearched :"X",
                     activeStocks: [],
                    addingError:false}) )
  .listen(port);


const wss = new SocketServer({ server });

wss.on('connection', (ws) => {
  console.log('Client connected');
  ws.on('close', () => console.log('Client disconnected'));
});

setInterval(() => {
  wss.clients.forEach((client) => {
    client.send(new Date().toTimeString());
  });
}, 1000);

But when I change it to this: 但是当我将其更改为:

const server = express()

.set('view engine', 'ejs') // set up ejs for templating
        .use(flash()) // use connect-flash for flash messages stored in session
      .listen(port);
    require('./app/routes.js')(server); 

    const wss = new SocketServer({ server });

    wss.on('connection', (ws) => {
      console.log('Client connected');
      ws.on('close', () => console.log('Client disconnected'));
    });

    setInterval(() => {
      wss.clients.forEach((client) => {
        client.send(new Date().toTimeString());
      });
    }, 1000);

..I get the TypeError: app.get is not a function ..我收到TypeError:app.get不是一个函数

Here are the contents of routes.js file: 以下是route.js文件的内容:

// app/routes.js
module.exports = function(app) {
    app.get('/', function(req, res) {
        var myStocks = require('./models/myStock'); 
        var showStocks = function(err, data){
            res.render('pages/indextimewithall.ejs', {
                     stockSearched :"X",
                    activeStocks: [],
                    addingError:false
                });
        }
        myStocks.find({isActive:true}).exec(showStocks);
    });
};

Thank you for any suggestions. 感谢您的任何建议。

Your clean up is just fine (although the readability and maintainability is a big issue...). 您的清理工作就很好了(尽管可读性和可维护性是一个大问题……)。 Here is a big gotcha for you: 这是给您的一个大陷阱:

app.listen method is not chainable, but app.use or app.METHOD series are. app.listen方法不可链接,但app.useapp.METHOD系列可以。 This means this method is not return itself at the end. 这意味着该方法不会在最后返回自身。 Therefore, you will get app.get is undefined, because your server variable is not an express instance. 因此,您将获得未定义的app.get ,因为您的server变量不是快速实例。

What you should do is break the chain, and defined as the following: 您应该做的是打破链条,并将其定义如下:

const app = express();
app.set('view engine', 'ejs');     // set up ejs for templating
app.use(flash());                  // use connect-flash for flash messages stored in session
require('./app/routes.js')(app);   // not recommended to clean up like this way though
app.listen(port);


const wss = new SocketServer({ server: app });
wss.on('connection', (ws) => {
  console.log('Client connected');
  ws.on('close', () => console.log('Client disconnected'));
});


setInterval(() => {
  wss.clients.forEach((client) => {
    client.send(new Date().toTimeString());
  });
}, 1000);

Note, in the above, I renamed your variable server as app . 注意,在上面,我将您的变量server重命名为app Just to follow the convention. 只是为了遵循惯例。

You can know if a method is chainable by running something like this: 您可以通过运行以下方法来知道方法是否可链接:

const app = express();
console.log(app === app.use((req, res, next) => next)));  // true
console.log(app === app.listen(3000));  // false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在App.js和route.js中使用Route之间的区别 - Difference between using Route in App.js and routes.js 如何 res.render 从 express js 反应应用程序路由? - How to res.render react app routes from express js? 在 routes.js 文件中导入商店导致 jest (vuejs) 错误 - import store in routes.js file cause error in jest (vuejs) 如何在Express(routes.js)中要求控制器(angularjs) - How to require a controller (angularjs) in express (routes.js) 从一个页面重定向到另一个页面而不在 Routes.js 文件中显示该文件路径 - Redirection from one page to another without showing that file path in Routes.js file 我如何使用外部路由.js所以我不必在app.js中定义我的路由? - How do I use external routes.js so I don't have to define my routes in app.js? Express.js 显示 req.body 未定义,路由从其他文件重新组合 - Express.js displaying the req.body undefined with routes regroup from other file 使用MEAN在route.js中具有多个带有参数的URI - Have multiple URIs with parameters in routes.js using MEAN 从route.js传递变量到我的.ejs页面 - passing a variable from routes.js to my .ejs page Express.js HTTP 500错误:页面与res.send(“ Some text”)一起使用; 但是使用res.render('file')时会导致错误吗? - Express.js HTTP 500 ERROR: Page works with res.send(“Some text”); but does error caused when using res.render('file');
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM