使用Hoppscotch发送PATCH请求时req.body.content为undefined的问题
问题解决:Express中PATCH请求req.body.content返回undefined
问题原因
你的Express项目仅配置了express.urlencoded()中间件,它只能解析application/x-www-form-urlencoded类型的请求体(比如传统表单提交的POST请求)。但Hoppscotch发送PATCH请求时,默认可能使用application/json格式的请求体,而项目未配置JSON请求体解析中间件,导致Express无法正确解析请求内容,进而出现req.body.content为undefined的情况。
解决方案
1. 添加JSON请求体解析中间件
在Express配置中新增express.json()中间件,让项目支持解析JSON格式的请求体。修改后的中间件配置如下:
app.use(express.urlencoded({extended: true})); // 添加JSON解析中间件 app.use(express.json());
2. 匹配Hoppscotch的请求配置
根据你选择的请求体格式,调整Hoppscotch的设置:
- JSON格式(推荐):
- 请求头设置
Content-Type: application/json - 请求体使用JSON结构:
{"content": "你的新内容"}
- 请求头设置
- 表单格式:
- 请求头设置
Content-Type: application/x-www-form-urlencoded - 请求体使用键值对形式:
content=你的新内容
- 请求头设置
修改后的完整代码示例
const express = require("express"); const app = express(); const path = require("path"); let port = 8080; const { v4: uuidv4 } = require('uuid'); // 同时配置urlencoded和json解析中间件 app.use(express.urlencoded({extended: true})); app.use(express.json()); app.set("views engine","ejs"); app.set("views",path.join(__dirname,"views")); app.use(express.static(path.join(__dirname,"public"))); let posts =[{ id: uuidv4(),username : "Naved",content : "I love coding",},{id: uuidv4(),username :"Noman",content : "I love studying",},{id: uuidv4(),username : "Saimoon",content:"Ilovecooking",}] ; app.get("/posts",(req,res)=>{ res.render("index.ejs", {posts}); }); app.get("/posts/new",(req,res)=>{ res.render("new.ejs") }) app.post("/posts",(req,res)=>{ let {username,content} = req.body; let id = uuidv4(); posts.push({id,username , content}); res.redirect("/posts"); }) app.get("/posts/:id",(req,res)=>{ let { id } = req.params; let post = posts.find ((p)=> id===p.id); res.render("show.ejs" ,{post}) }) app.patch("/posts/:id",(req,res)=>{ let { id } = req.params; let newContent = req.body.content ; let post = posts.find ((p)=> id === p.id); post.content = newContent; console.log(post); res.send("patch request send succesfully"); }) app.listen(port,()=>{ console.log(`app is listening at the port ${port}`); });
内容的提问来源于stack exchange,提问作者Naved Khan
相关产品推荐
相关产品推荐

