我正在创建一个博客网络应用程序,用户可以在其中创建文章。一旦他们点击新文章,就会有一个发布文章按钮,该按钮与一个发布请求相关联,该请求与我的 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>newrouter.get('/new', (req, res)=>{ res.render('articles/new', { article: new Article() })})//When you do the post request, it redirects u to /articlesrouter.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)})
1 回答
冉冉说
TA贡献1877条经验 获得超1个赞
首先,确保将其安装到正确的位置。似乎错误表明它无法获取 /article/id,但可能是您的意思是 /article s /id?
检查您正在使用的 id 是否是您想要获取的正确 id。
此外,您的错误是“无法获取 /article/5ef90e3089b93f1164842e6c”,它不包括域的第一部分(即 localhost 或www.example.com)。你不小心把那部分漏掉了吗?
你如何附加这个路由器(即主文件中的代码是什么)
此外,您的整个文件中有 1 个分号,是否有任何运行时错误?
也许,在“/article(s)”上设置一个获取请求,以响应所有文章(及其 id!),然后验证您使用的是正确的 id。
添加回答
举报
0/150
提交
取消
