我正在创建一个博客网络应用程序,用户可以在其中创建文章。一旦他们点击新文章,就会有一个发布文章按钮,该按钮与一个发布请求相关联,该请求与我的 JS 文件中的 router.post 函数相关联,该文件包含我的所有路由。在这个函数中,我正在检索我的文章数据(描述、标题、降价等)。在尝试部分,我正在保存,然后使用文章 ID 重定向到 URL。我已经设置了另一条与所有 id 路由相关的路由,我试图在其中显示对象的 ID,但出现无法获取错误。我想知道为什么我收到此错误,因为正在接收 ID。具体错误是:“Cannot GET /article/5ef90e3089b93f1164842e6c”。我将不胜感激任何帮助
const express = require('express')
const router = express.Router();
const Article = require('./../models/article')
//on articles/new, render new.ejs in articles>new
router.get('/new', (req, res)=>{
res.render('articles/new', { article: new Article() })
})
//When you do the post request, it redirects u to /articles
router.post('/', async (req, res)=>{
const message = "hello";
let article = new Article({
//record information
title: req.body.title,
description: req.body.description,
markdown: req.body.markdown
})
try{
//save information, send to article/id
article = await article.save()
console.log(article.id)
res.redirect(`/article/${article.id}`)
} catch (e) {
//rerender with preloaded data if there is an error
res.render('articles/new', { article: article })
console.log(e)
}
})
router.get('/:id', (req, res) => {
//const article is the article with this specific id
res.send(req.params.id)
})
冉冉说
相关分类