Express.js应用程序错误:当尝试访问某些路由时,浏览器处于加载状态

问题描述 投票:0回答:2

我正在使用ExpressEJS和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');
};

我在做什么错?

node.js express ejs
2个回答
0
投票

在输入文件index.js中,您以错误的方式注册了路由。要注册路线,您必须使用app.use()而不是app.get()app.get('/', postsRoute);更改为app.use('/', postsRoute);


0
投票

唯一的原因是因为您两次使用getindex.js中的第一个,dashboard.js中的第二个。您不应该这样做。

© www.soinside.com 2019 - 2024. All rights reserved.