检索子路由时的Node.js 404

时间:2018-12-16 03:53:11

标签: javascript node.js

我正在尝试制作一个具有多个路由器的nod​​e.js站点。我遇到的问题是URL localhost:3000/forms/createForm返回404 not found错误。我对Node很陌生,所以我不是100%确定要搜索的内容。我也是Stack Overflow的新手,所以如果我错过了任何事情,请告诉我:)

注意:我的路由器已在我的app.js文件中注册。

项目结构:

app
|-routes
|    |-index.js
|    |-forms.js
|-views
     |-layout
     |-forms
         |-index.hbs
         |-createForm.hbs 

这是我的forms.js:

var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');

/* GET home page. */
router.get('/', function(req, res, next) {
    res.render('forms/index', { title: 'Forms' });
});

router.get('/createForm', function(req, res) {
    res.render('forms/createForm', { title: 'Create Form' })
});

module.exports = router;

这是服务器活动:

GET /forms/ 200 1.461 ms - 2480
GET /stylesheets/lightTheme.css 304 0.443 ms - -
GET /forms/createForm 404 5.085 ms - 4039
GET /stylesheets/lightTheme.css 304 0.508 ms - -

App.js:

var formsRouter = require('./routes/forms');
...
app.use('/forms', formsRouter);

1 个答案:

答案 0 :(得分:1)

您注册了/createForm路由,而不是/forms/createForm。另外,您只有一个路由器。如果要使用多个路由器,可以执行以下操作:

var express = require('express');

var mongoose = require('mongoose');

var formsRouter = express.Router();
formsRouter.get('/createForm', function(req, res) {
    res.render('forms/createForm', { title: 'Create Form' })
});

var router = express.Router();
router.get('/', function(req, res, next) {
    res.render('forms/index', { title: 'Forms' });
});

router.use('/forms', formsRouter);

module.exports = router;