Nodejs Express:路由在单独的文件中 [英] Nodejs Express: Routes in separate files
问题描述
我写了我的app.js,其中包括主文件中的所有路由,并且一切运行正常.我的目标是通过将路径移动到其他文件中来使项目更清晰,但是它不起作用. 我正在传递一个对象而不是中间件函数,而且我不知道如何以正确的方式修复它.
I write my app.js including all the routes in the main file and everything was working well. After my goal was to make the project more clear by moving the routes in a different files but it is not working. I'm passing an object instead of a middleware function and I don't know how to fix it in the right way.
这是我的app.js文件:
So this is my app.js file:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var myRoutes = require('./app/routes/myRoutes.js');
...
//parser for getting info from POST and/or URL parameters
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//for log requests to console
app.use(morgan('dev'));
app.use('/myRoutes', myRoutes);
app.get('/',function(req,res){
res.end('Welcome Page!');
});
//Server Start
app.listen(port);
console.log('server start at port ' + port);
app/routes/myRoutes.js包含以下代码:
And the app/routes/myRoutes.js contains the following code:
var express = require('express');
...
var myRoutes = express.Router();
myRoutes.get('/users',function(req,res){
...
});
myRoutes.post('/setup',function(req,res){
...
});
myRoutes.post('/remove', function(req,res){
...
});
module.export = myRoutes;
我也尝试过:
var express = require('express');
var myRoutes = express.Router();
myRoutes.route('/')
.get(function(req, res, next){
res.end('myRoute Get');
})
.post(function(req, res, next){
res.end('myRoute Post');
});
module.export = myRoutes;
但是再次似乎没有传递中间件功能.
But again it seems not passing a middleware function.
推荐答案
我的第二个选项代码
var express = require('express');
var myRoutes = express.Router();
myRoutes.route('/')
.get(function(req, res, next){
res.end('myRoute Get');
})
.post(function(req, res, next){
res.end('myRoute Post');
});
module.export = myRoutes;
工作正常!我只是写错了方式
is working fine! I just write it in a wrong way
module.export = myRoutes;
的
module.exports = myRoutes;
这篇关于Nodejs Express:路由在单独的文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!