在node.js中使用express路由文件夹

时间:2017-08-25 16:11:22

标签: node.js express handlebars.js

我决定将我的路线从我的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;

和routes / 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中的管道中时它起作用,但是因为删除它们已经坏了。任何建议将不胜感激!

1 个答案:

答案 0 :(得分:2)

此问题与路由本身有关。说我们正在寻找/关于:

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中有另一个/关于这个,这将在localhost / about / about

呈现