我正在使用Express,EJS和MongoDB开发博客应用程序。
出于某种原因,我无法识别,当我尝试在浏览器中访问:http://localhost:3000/dashboard
时,它(浏览器)陷入了加载状态,并且从未实际加载仪表板路线。
在“ entry” index.js文件中,我有:
const express = require('express');
const dotenv = require('dotenv');
const mongoose = require('mongoose');
const path = require('path');
const morgan = require('morgan');
const expressLayouts = require('express-ejs-layouts');
const app = express();
dotenv.config();
//Conect to MONGODB
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
console.log('conected');
});
mongoose.connection.on('error', err => {
console.log(`DB connection error: ${err.message}`);
});
// Set static directory
app.use(express.static(path.join(__dirname, 'public')));
// Set views directory
app.set('views', path.join(__dirname, 'views'));
// Set view engine
app.set('view engine', 'ejs');
// Use Express Layouts
app.use(expressLayouts);
// Middleware
app.use(morgan('dev'));
// Bring the Posts Routes
const postsRoute = require('./routes/front-end/posts');
// Get Posts
app.get('/', postsRoute);
// Get Single Post
app.get('/:id', postsRoute);
// Bring the Dashboard
const dashboardRoute = require('./routes/admin/dashboard');
// Get Dashboard
app.get('/dashboard', dashboardRoute);
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
在仪表板路线(routes \ admin \ dashboard.js)中,我有:
const express = require('express');
const dashboardController = require('../../controllers/admin/dashboard');
// Express router
const router = express.Router();
// Dysplay Dashboard
router.get('/dashboard', dashboardController.displayDashboard);
module.exports = router;
同时在仪表板控制器:
const Post = require('../../models/post');
exports.displayDashboard = (req, res, next) => {
res.send('Dashboard');
};
我在做什么错?
在输入文件index.js
中,您以错误的方式注册了路由。要注册路线,您必须使用app.use()
而不是app.get()
将app.get('/', postsRoute);
更改为app.use('/', postsRoute);
唯一的原因是因为您两次使用
get
。index.js
中的第一个,dashboard.js
中的第二个。您不应该这样做。