[英]Cannot Load Routes in ./src/routes/index.js from ./app.js
very new to nodejs here. 这里的nodejs非常新。 I've tried to put routes in app.js
without problem. 我试图将路由放在app.js
没有问题。 However, after moving all the routes to a separate file under PROJECT_DIR/src/routes/index.js
, and then I open the page in browser it says "Cannot GET /wines
". 但是,将所有路由移动到PROJECT_DIR/src/routes/index.js
下的单独文件后,然后在浏览器中打开页面,显示“无法获取/wines
”。 Here's code in app.js
and src/routes/index.js
: 这是app.js
和src/routes/index.js
的代码:
// app.js
var express = require('express');
var app = express();
var path = require('path');
global.app = express();
require('./src/routes/index');
// also tried: require(path.join(__dirname, './src/routes/index'));
global.server = app.listen(3000, '0.0.0.0', function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
// ./src/routes/index.js
// tried console.error(app); and it printed all the stuff about app in the server log
app.get('/wines', function(req, res) {
res.send([{name:'w1'}, {name:'w2'}]);
});
app.get('/', function (req, res) {
res.send('Hello World!');
});
I'm sure I'm missing something. 我确定我想念什么。 Any help is appreciated! 任何帮助表示赞赏!
Problem 问题
Honestly, I am not sure why what you are doing does not work. 老实说,我不确定为什么您的操作不起作用。
The file can be found because otherwise, Node would throw an error, and the fact that you can access app
from the routes file means app
is accessible. 可以找到该文件,因为否则,Node会引发错误,并且您可以从路由文件访问app
的事实意味着该app
是可访问的。
I have a suspicion that this may be due to garbage collection -- because you do not hold a reference to the module, it may be preemptively destroyed. 我怀疑这可能是由于垃圾回收造成的 -因为您没有持有对模块的引用,所以它可能会被抢先破坏。
What's more, there is a construct in Express called a router that probably exists for this exact purpose. 更重要的是,Express中有一个称为路由器的构造可能正是出于这个确切目的而存在。
Solution 解
While I'm not sure about the problem I am sure about the solution -- use a router, like this: 虽然我不确定该问题,但我对该解决方案也很确定-使用路由器,如下所示:
var express = require('express');
var router = express.Router();
router.get('/wines', function(req, res) {
res.send([{name:'w1'}, {name:'w2'}]);
});
router.get('/', function (req, res) {
res.send('Hello World!');
});
module.exports = router;
And then in your app.js
file, do this: 然后在您的app.js
文件中,执行以下操作:
var routes = require('./routes/index');
app.use('/', routes);
Another benefit of routers is that you do not have to pollute the global object anymore.. 路由器的另一个好处是您不必再污染全局对象。
You need to use export in index.js 您需要在index.js中使用export
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index');
});
module.exports = router;
and use it like this in app.js 并在app.js中像这样使用
var router = require('./src/routes/index');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.