MERN+MySQL博客应用重复POST请求触发ERR_HTTP_HEADERS_SENT错误求助
问题排查与修复
核心错误原因
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client 错误的本质是:同一个HTTP请求的处理流程中,你尝试向客户端发送了两次响应。
在你的后端createBlog控制器中,先通过res.json()发送了JSON格式响应,之后又调用return res.send('creando blogs')再次发送文本响应。HTTP协议规定一个请求只能对应一个响应,重复发送会触发这个错误,甚至导致服务器连接异常。
修复后端控制器代码
修改createBlog函数,只保留一个响应输出。推荐返回统一的JSON格式响应,删除多余的res.send()语句:
export const createBlog = async(req, res) => { const {name, post} = req.body const [result] = await pool.query('INSERT INTO blogs (name, post) VALUES (?, ?)',[ name, post ]) // 只保留这一个响应语句,可将提示文本合并到JSON中 res.json({ id: result.insertId, name, post, message: 'creando blogs' }) console.log(result) }
额外优化建议
前端代码小问题修正
- 将
targeted变量移到handleSubmit函数内部,避免作用域混淆:
const handleSubmit = async (e) => { e.preventDefault(); const targeted = {name: newUser, post: newPost} console.log(targeted) try { const response = await createBlogRequest(targeted) console.log(response) } catch (error) { console.error(error) } }
- 修改Axios请求函数,返回响应结果,避免前端
console.log(response)输出undefined:
import axios from 'axios' export const createBlogRequest = async (blog) =>{ return await axios.post('http://localhost:4000/blogs', blog) }
后端错误捕获增强
给数据库操作添加try-catch块,避免未处理异常导致服务器崩溃:
export const createBlog = async(req, res) => { try { const {name, post} = req.body const [result] = await pool.query('INSERT INTO blogs (name, post) VALUES (?, ?)',[ name, post ]) res.json({ id: result.insertId, name, post, message: '博客创建成功' }) console.log(result) } catch (error) { console.error('数据库操作错误:', error) res.status(500).json({error: '创建博客失败,请重试'}) } }
内容的提问来源于stack exchange,提问作者skinnyleonard
相关产品推荐
相关产品推荐

