JDi*_*522 3 routing node.js express
我是Express的新手.我正在做我的路由的方式是踢回错误.
这是我的相关代码:
app.js
var express = require('express')
, routes = require('./routes')
, http = require('http')
, path = require('path')
, firebase = require('firebase');
...
// Routing
app.get('/', routes.index);
app.get('/play', routes.play);
Run Code Online (Sandbox Code Playgroud)
index.js和play.js
exports.index = function(req, res){
res.sendfile('views/index.html');
};
exports.play = function(req, res){
res.sendfile('views/play.html');
};
Run Code Online (Sandbox Code Playgroud)
这是错误:
错误:.get()需要回调函数但得到[对象未定义]
它在app.js中引用了这一行
app.get('/play', routes.play);
Run Code Online (Sandbox Code Playgroud)
我迷失了为什么这不起作用,因为代码结构是相同的路由到我的索引页面和索引页面加载完美.
有任何想法吗?谢谢
这个问题可能是这routes.play是undefined一个时function的预期.
console.log(typeof routes.play); // ...
Run Code Online (Sandbox Code Playgroud)
如果你routes被分成多个文件至少作为评论," index.js和play.js "建议:
// routes/index.js
exports.index = function(req, res){
res.sendfile('views/index.html');
};
Run Code Online (Sandbox Code Playgroud)
// routes/play.js
exports.play = function(req, res){
res.sendfile('views/play.html');
};
Run Code Online (Sandbox Code Playgroud)
要求目录通常只包括index.js.所以,你仍然需要require('./play')自己在某个地方.
你可以在其中"转发"它index.js:
exports.index = function(req, res){
res.sendfile('views/index.html');
};
var playRoutes = require('./play');
exports.play = playRoutes.play;
Run Code Online (Sandbox Code Playgroud)
或者:
exports.play = require('./play');
Run Code Online (Sandbox Code Playgroud)
app.get('/play', routes.play.play);
Run Code Online (Sandbox Code Playgroud)或直接要求它app.js:
var express = require('express')
, routesIndex = require('./routes')
, routesPlay = require('./routes/play')
// ...
// Routing
app.get('/', routesIndex.index);
app.get('/play', routesPlay.play);
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
4562 次 |
| 最近记录: |