简体   繁体   中英

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. I am getting a TypeError, explained below. 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

Here are the contents of routes.js file:

// 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. 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.

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 . 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM