Express.js 中的渲染问题:主页、登录、注册不显示

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

我的 Express.js 应用程序遇到了一个问题,其中没有任何视图(

home.ejs
login.ejs
register.ejs
)似乎正在渲染,并且我遇到了“无法访问此网站”的问题- 连接已重置”错误。作为网络开发的新手,我正在寻求帮助来识别和解决问题。

这是我的代码:

import bodyParser from "body-parser";
import express from "express";
import mongoose from "mongoose";
import bcrypt from "bcrypt";

const app = express(); 
const port = 9000;

app.use(express.static('public'));
app.set('view engine', 'ejs');  
app.use(bodyParser.urlencoded({ extended: true })); 
mongoose.connect("mongodb://localhost:27017/usersdb"); 

const userSchema = new mongoose.Schema({
    username: String,
    password: String
});

const User = mongoose.model('User', userSchema); 

app.get('/', function(req, res) {
    try {
        res.render("home"); 
    } catch (error) {
        console.error(error, 'Home not Rendering');
        res.status(500).send('Internal Server Error');
    }
});

app.get('/register', function(req, res) {
    res.render("register")
});

app.get('/login', function(req, res) {
    res.render("login")
});

app.post('/register', async (req, res) => {
    try {
        const hashedPassword = await bcrypt.hash(req.body.password, 10);
        const newUser = new User({
            username: req.body.username,
            password: hashedPassword
        });
        await newUser.save();
        res.redirect('/login'); // Redirect to login page after successful registration
    } catch (error) {
        console.error(error, 'Error during registration');
        res.status(500).send('Internal Server Error');
    }
});

app.listen(port, () => {
    console.log(`The server is running on http://localhost:${port}`);
});

模板目录: 确保您的视图目录位于正确的位置并且包含您的 EJS 文件(home.ejs、register.ejs 和 login.ejs)。默认情况下,Express 会在项目根目录中查找视图目录。

目录图片:https://i.stack.imgur.com/khWXf.png

确保视图目录结构正确并包含必要的 EJS 文件。

模板渲染: 确保正确设置 EJS 模板并包含渲染所需的 HTML/EJS 代码。例如,在您的 home.ejs、register.ejs 和 login.ejs 文件中,您应该具有适当的 EJS 语法来呈现内容。

查看引擎设置: 仔细检查您的视图引擎设置。您已使用 app.set('view engine', 'ejs'); 将视图引擎设置为 EJS。确保 EJS 模块已安装 (npm install ejs) 并在 package.json 文件中列为依赖项。

重定向: 在 /register 路由中,您将用户保存到数据库,但没有响应或重定向。考虑将用户重定向到另一个页面或呈现成功消息。

javascript node.js express ejs
1个回答
0
投票

Express 不知道您保存 .ejs 文件的目录。所以你需要声明它:

app.set('views', path.resolve('views'));

不要忘记导入文件顶部的

path
import path from 'path';

我制作的示例:https://stackblitz.com/edit/stackblitz-starters-tcsbg8?file=index.js

官方示例:https://github.com/mde/ejs/blob/main/examples/express/app.js

您更正后的代码:

import bodyParser from "body-parser";
import express from "express";
import mongoose from "mongoose";
import bcrypt from "bcrypt";
import path from "path";

const app = express(); 
const port = 9000;

app.use(express.static('public'));
app.set('views', path.resolve('views'));
app.set('view engine', 'ejs');  
app.use(bodyParser.urlencoded({ extended: true })); 
mongoose.connect("mongodb://localhost:27017/usersdb"); 

const userSchema = new mongoose.Schema({
    username: String,
    password: String
});

const User = mongoose.model('User', userSchema); 

app.get('/', function(req, res) {
    try {
        res.render("home"); 
    } catch (error) {
        console.error(error, 'Home not Rendering');
        res.status(500).send('Internal Server Error');
    }
});

app.get('/register', function(req, res) {
    res.render("register")
});

app.get('/login', function(req, res) {
    res.render("login")
});

app.post('/register', async (req, res) => {
    try {
        const hashedPassword = await bcrypt.hash(req.body.password, 10);
        const newUser = new User({
            username: req.body.username,
            password: hashedPassword
        });
        await newUser.save();
        res.redirect('/login'); // Redirect to login page after successful registration
    } catch (error) {
        console.error(error, 'Error during registration');
        res.status(500).send('Internal Server Error');
    }
});

app.listen(port, () => {
    console.log(`The server is running on http://localhost:${port}`);
});

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