gpt4 book ai didi

node.js - Node 应用程序中的索引页面仅路由到第一个显示页面

转载 作者:太空宇宙 更新时间:2023-11-04 01:55:09 24 4
gpt4 key购买 nike

我正在使用 node/express/psql 构建一个目标应用程序。当我单击索引页面上的目标时,我希望它链接到该目标的显示页面。然而,每一个都链接到 id=1 的目标。我很困惑,因为我首先用来打印对象的 .forEach 正在工作,只是链接不起作用。任何帮助将不胜感激!

索引.ejs:

<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="styles.css">
<meta charset="UTF-8">
<title>Goals</title>
</head>
<body>
<h1>Here's a look at all of your goals!!</h1>
<a href="/goals/new">New Goal?</a>
<% goals.forEach(goal => { %>
<div class="goal-container">
<h2><a href="<%= `/goals/${goal.id}` %>"><%= goal.description %></a></h2>
<p><%= goal.step1 %></p>
<p><%= goal.step2 %></p>
<p><%= goal.step3 %></p>
<p><%= goal.step4 %></p>
</div>
<% }) %>
</body>
</html>

Controller :

const Goal = require('../models/goal');
const goalsController = {};

goalsController.index = (req, res) => {
Goal.findAll(req.user.id)
.then(goal => {
res.render('goals/', { goals: goal });
})
.catch(err => {
res.status(400).json(err);
});
};

goalsController.show = (req, res) => {
Goal.findById(req.params.id)
.then(goals => {
console.log('goals show');
res.render(`goals/show`, { goals:goals })
})
.catch(err => {
res.status(400).json(err);
});
};

module.exports = goalsController;

路线:

const express = require('express');
const goalsController = require('../controllers/goals-controllers');
const goalsRouter = express.Router();

goalsRouter.get('/', goalsController.index);
goalsRouter.get('/new', goalsController.new);
goalsRouter.get('/:id', goalsController.show);
goalsRouter.get('/:id/edit', goalsController.edit);
goalsRouter.put('/:id', goalsController.update);
goalsRouter.post('/', goalsController.create);
goalsRouter.delete('/:id', goalsController.delete);

module.exports = goalsRouter;

型号:

const db = require('../db/config');
const Goal = {};

Goal.findAll = id => {
return db.query(`SELECT * FROM goals JOIN users ON goals.user_id = users.id WHERE goals.user_id = $1`, id)
};


Goal.findById = id => {
console.log('findbyId')
return db.oneOrNone(`SELECT * FROM goals WHERE id = $1`, [id])
};

module.exports = Goal;

提前致谢!

最佳答案

我相信您的 index.ejs 有问题

尝试替换<h2><a href="<%= `/goals/${goal.id}` %>"><%= goal.description %></a></h2>

<h2><a href="/goals/<%= goal.id %>"><%= goal.description %></a></h2>

关于node.js - Node 应用程序中的索引页面仅路由到第一个显示页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48254111/

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