【问题标题】:I don't understand why it's looking for an ID instead of a view我不明白为什么它在寻找 ID 而不是视图
【发布时间】:2021-07-11 23:52:02
【问题描述】:

我正在尝试到达某个路线,其中包含一个表单,但由于某种原因它正在寻找一个 id。我将分享我的路线、我的观点和错误。

//celebrities routes 

const express = require('express');
const router = express.Router();
const Celeb = require('../model/celebrity.model')

router.get('/celebrities', (req, res) => {
    Celeb.find()
        .then(AlltheModels => {
            console.log(AlltheModels)
            res.render('celebrities/index', { celebs: AlltheModels })
        })
        .catch(error => console.log('error while getting the celebrities', error))
})

router.get('/celebrities/:id', (req, res) => {
    const celebId = req.params.id
    console.log(celebId)
    Celeb.findById(celebId)

        .then(OneCeleb => {
            console.log(OneCeleb)
            res.render('celebrities/show', { celebOne: OneCeleb })
        })

        .catch(error => console.log('there was an error by retrieving..', error))
})

//NEW celebrities

router.get('/celebrities/new', (req, res) => {

    res.render('celebrities/new')
})

router.post('/celebrities', (req, res) => {
    const { name, occupation, catchPhrase } = req.body;
    Celeb.create({ name, occupation, catchPhrase })
        // .then(CelebNew => {
        //      CelebNew.save()
        //  console.log(CelebNew + '...has been entered')
        // })
        .then(() => res.redirect('/celebrities'))
        .catch(error => `There was an error of ${error}`, err)
})

module.exports = router;

这是应该指向表单视图的视图

<div>
    <a href="/celebrities/new">Create a new Celebrity</a>
</div>


<div>
    {{#each celebs}}
    <a href="/celebrities/{{_id}}">
        <h2>{{this.name}}</h2>
    </a>
    {{/each}}
</div>

这是错误

"GET /celebrities/new - - ms - -

...检索出错.. CastError: Cast to ObjectId failed for value "new" at path "_id" for model "Celeb" 在 model.Query.exec (/mnt/c/Users/carlo/documents/ironhack/labs/lab-mongoose-movies/starter-code/node_modules/mongoose/lib/query.js:4408:21)"

据我了解,问题出在这条路线上

router.get('/celebrities/:id', (req, res) => {
    const celebId = req.params.id
    console.log(celebId)
    Celeb.findById(celebId)

        .then(OneCeleb => {
            console.log(OneCeleb)
            res.render('celebrities/show', { OneCeleb })
        })

        .catch(error => console.log('there was an error by retrieving..', error))
})

但我不知道错误的原因或位置,或者为什么它试图寻找新的 Id,是车把助手吗?。

【问题讨论】:

  • 而不是 URL 末尾的“/new”,而是“/0”。路由参数 ID 始终应为数字。我不确定这是否与 Celeb.findById 混淆,但您只需要返回一个新实例

标签: javascript node.js express routes handlebars.js


【解决方案1】:

您的问题是路径 /celebrities/new 与模式 /celebrities/:id 匹配。

当您向路径 /celebrities/new 发出 GET 请求时,Express 会按顺序查看所有已注册的路由,试图找到匹配项。当 Express 找到注册的路由时,/celebrities/:id 认为这是一个匹配,因为请求路径与模式匹配 - 它以“/celebrities/”开头,后跟一个任意字符串值,它解释为 id 参数(“新”)。

Express 永远不会为/celebrities/new GET 路由提供服务,因为/celebrities/:id 将始终是第一个匹配项。

为了让 Express 找到 /celebrities/new 路由,它必须在/celebrities/:id 路由之前注册。您只需将router.get('/celebrities/new'... 代码移到router.get('/celebrities/:id',... 代码之上。

【讨论】:

  • 天哪,谢谢!它有效!那么在 express 中路由时的最佳做法是什么?
  • 这并不是真正特定于 Express 中的路由。在任何情况下,为了查找匹配项而循环遍历列表,您都希望将带有通配符的值放在没有通配符的值之后。即,如果您想包含一个包罗万象的路径 (/*),您需要最后注册它,否则它将捕获 每个 请求(使用相同的 HTTP 方法)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-03
  • 1970-01-01
  • 2011-02-21
  • 1970-01-01
  • 2015-04-02
  • 2021-11-18
  • 1970-01-01
相关资源
最近更新 更多