【问题标题】:Routing folders with express in node.js在 node.js 中使用 express 路由文件夹
【发布时间】:2017-08-26 04:32:39
【问题描述】:

我决定将我的路线从我的 app.js 中取出并放入它们自己的单独文件夹中,但现在该站点将加载把手文件以用于索引,而不是用于关于或联系 - 我很困惑,需要帮助以换取+1。

// Import the express module
var express = require('express');
var path = require("path");
var bodyParser = require("body-parser");

var index = require('./routes/index');
var about = require('./routes/about');
var contact = require('./routes/contact');

var handlebars = require('express-handlebars').create({defaultLayout:'main'});

var app = express();

// Block the header from containing information
// about the server
app.disable('x-powered-by');


app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'handlebars');
app.engine('handlebars', handlebars.engine);

//set static folder
app.use(express.static(__dirname + '/public'));//allows access to public directory

//set bower folder
app.use('/bower_components',  express.static(__dirname + '/bower_components'));//defines bower components directory

//body parser MW
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

app.set('port', process.env.PORT || 1337);// Defines the port to run on


app.use("/", index);
app.use("/about", about);
app.use("/contact", contact);


app.use(function(req, res){
    res.type('text/html');
    res.status(404);
    res.render('404');
});

app.use(function(err, req, res, next){
    console.error(err.stack);
    res.status(500);
    res.render('500');
});


app.listen(app.get('port'), function(){
    console.log("Express started on http://127.0.0.1:" + app.get('port') + ' Press Ctrl+C to terminate');
    })

这是 routes/index.js 文件:

    var express = require("express");
    var router = express.Router();

    // Defines the base url
    router.get('/', function(req, res, next){
      // Point at the home.handlebars view
      res.render('home');
    });

    module.exports = router;

还有路由/about.js

    var express = require("express");
    var router = express.Router();

    router.get('/about', function(req, res, next){
      res.render('about');
    });

    module.exports = router;

当我转到 localhost/contact 时,我得到了我的 404 页面,/about 也是如此。

视图位于 app/views 中,当我将它们放在 app.js 中的管道中时它可以工作,但自从删除它们后它就坏了。任何建议将不胜感激!

【问题讨论】:

    标签: node.js express handlebars.js


    【解决方案1】:

    此问题与路由本身有关。假设我们正在寻找 /about :

    app.use("/about", about);
    

    然后应用会查看 about 的路由文件夹并找到以下内容。

    var express = require("express");
    var router = express.Router();
    
    router.get('/about', function(req, res, next){
      res.render('about');
    });
    
    module.exports = router;
    

    因为我在 router.get 中有另一个 /about ,所以它会在 localhost/about/about 上呈现

    【讨论】:

      猜你喜欢
      • 2018-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-10
      • 2015-01-30
      • 1970-01-01
      • 2021-09-07
      相关资源
      最近更新 更多