我有一个快递网站,我正在尝试将其转换为使用routes.js文件进行清理。我得到一个TypeError,如下所述。我看过this和this,但我仍然无法弄明白。目前该网站使用以下几行:
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);
但是当我改变它时:
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);
..我得到TypeError:app.get不是函数
以下是routes.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);
});
};
感谢您提出任何建议。
答案 0 :(得分:0)
你的清理工作很好(尽管可读性和可维护性是个大问题......)。这是一个很大的问题:
app.listen
方法不可链接,但app.use
或app.METHOD
系列是可链接的。这意味着此方法最终不会返回。因此,您将app.get
未定义,因为您的server
变量不是快速实例。
你应该做的是打破链条,并定义如下:
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);
注意,在上文中,我将变量server
重命名为app
。只是为了遵循惯例。
您可以通过运行以下内容来了解方法是否可链接:
const app = express();
console.log(app === app.use((req, res, next) => next))); // true
console.log(app === app.listen(3000)); // false