gpt4 book ai didi

javascript - 如何在 Express.js 中为路由的子路径呈现不同的 View ?

转载 作者:行者123 更新时间:2023-11-30 16:12:11 25 4
gpt4 key购买 nike

我正在开发一个 Node js + Express + express-handlebars 应用程序。在我的 app.js 文件中,我将我的路线定义为

var students = require('./routes/students');
var faculty = require('./routes/faculty');

app.use('/students', students);
app.use('/faculty', faculty);

路径文件夹中存在 students.jsfaculty.js。因此,当用户转到带有/students 的路径时,我在 students.js 中执行以下操作:

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

router.get('/', function(req, res){
res.render('students_view', {
msg : 'this is student page'
});
});

module.exports = router;

students_view 是 views 文件夹中的 express-handlebars 页面。现在假设我想添加一个新学生,当我在 student_view 页面上按下添加按钮时,它会将我带到一个具有以下 url 的页面:/students/add

在该页面上,我需要呈现不同的 View (准确地说是一种形式)。在我的 app.js 中,我正在执行以下操作:

app.use('/student/add', students);

在我的 student.js 中,我正在执行以下操作:

router.get('/add', function(req, res){
res.render('students_add', {
msg : 'this is student add page'
});
});

不过,还是会去之前的router.get('/')渲染student_view页面。如何为此路径呈现不同的 View ?它是否需要自己的单独路由(比如 student_add.js),我可以在其中处理获取和发布?

最佳答案

您正在使用 app.js 中的路由。将您的 student.js 更改为

router.get('/', function(req, res){
res.render('students_view', {
msg : 'this is student page'
});
});
router.get('/add', function(req, res){
res.render('students_add', {
msg : 'this is student add page'
});
});

app.js

app.use('/students', students); 
// not need of app.use('/students/add', students);

关于javascript - 如何在 Express.js 中为路由的子路径呈现不同的 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36082078/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com