节点应用中的索引页面仅路由到第一个显示页面

时间:2018-01-14 21:00:40

标签: node.js express ejs psql

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

index.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>

控制器:

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;

提前致谢!

1 个答案:

答案 0 :(得分:0)

我相信您的index.ejs

有问题

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

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