Express js:单独的控制器和路由器文件在路由上返回404错误

时间:2017-03-30 06:03:22

标签: javascript node.js express

我想将app.js文件中的所有路由分成seprat  route文件,它将从控制器目录加载控制器。

这是我的文件夹结构

<project folder>
   controllers
         testController.js
   routes
        route.js
app.js

这是我的testController.js

module.exports = {
    getMovie : function(req, res){
        //do something
        res.send('respond with test resource');
    },
    postMovie : function(req, res){
        //do something
    }
}
route.js目录下的

route

var express = require('express');
//load the contrller
var test = require('../controllers/testController.js');
var router = express.Router();

router.route('/hello').get(test.getMovie);

module.exports = router;

当我访问我的路线localhost:3000/hello时,我收到404错误。

我刚试过这个问题的解决方案separate file for routes in express

app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes');

var app = express();
app.use('api',routes);

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

1 个答案:

答案 0 :(得分:0)

请更新

var routes = require('./route')

var routes = require('./routes/route');