使用XMLHttpRequest发起POST请求的错误排查求助
问题排查与解决方案
嘿,我一眼就瞅到了前后端数据格式不匹配的核心问题——这就是你的POST请求没法正常工作的关键!咱们一步步拆解修复:
1. 前端请求的格式冲突是罪魁祸首
你的前端代码里藏着两个矛盾点:
- 你设置了请求头
Content-type: application/x-www-form-urlencoded,这告诉后端要接收表单编码格式的数据(比如key1=value1&key2=value2) - 但你调用
send()时,却用了JSON.stringify(json)处理参数,而且传入的参数本身就是表单格式的字符串——相当于把表单字符串又套了一层JSON壳,后端根本没法解析!
修正方案二选一:
方案A:继续用表单编码格式
直接发送表单字符串,不要多此一举用 JSON.stringify:
const CHEMIN_AU_SERVEUR = "http://localhost:3000/api/stuff"; const func_that_post_the_card_created = (path, formData) => { const request_projets_post = new XMLHttpRequest(); request_projets_post.open("POST", path, true); request_projets_post.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // 直接发送表单格式字符串,去掉JSON.stringify request_projets_post.send(formData); }; func_that_post_the_card_created(CHEMIN_AU_SERVEUR, "title=title&description=description&imageUrl=imageUrl&href=href&github_href=github_href");
方案B:更推荐的JSON格式传输
和后端的 bodyParser.json() 匹配,传输JSON格式数据:
const CHEMIN_AU_SERVEUR = "http://localhost:3000/api/stuff"; const func_that_post_the_card_created = (path, data) => { const request_projets_post = new XMLHttpRequest(); request_projets_post.open("POST", path, true); // 设置正确的JSON类型请求头 request_projets_post.setRequestHeader("Content-type", "application/json"); // 把对象转成JSON字符串发送 request_projets_post.send(JSON.stringify(data)); }; // 传入对象格式的数据,更易维护 func_that_post_the_card_created(CHEMIN_AU_SERVEUR, { title: "title", description: "description", imageUrl: "imageUrl", href: "href", github_href: "github_href" });
2. 后端解析配置对应调整
如果选方案A用表单编码格式,需要给后端加一个表单解析中间件:
// 在app.use(bodyParser.json())后面添加 app.use(bodyParser.urlencoded({ extended: true }));
如果选方案B用JSON格式,当前的 bodyParser.json() 完全没问题,不用改。
3. 调试小技巧帮你快速定位问题
- 打开浏览器开发者工具的Network标签,查看POST请求的Payload和Headers,确认发送的数据格式和请求头是否匹配
- 在后端POST路由里先打印
req.body,看看是否能正确接收到数据:
app.post("/api/stuff", (req, res, next) => { console.log("接收到的请求体:", req.body); // 调试用,确认数据是否正确 const projet = new ProjectScheme({ ...req.body }); projet.save() .then(() => res.status(201).json({ message: "Projet enregistré !" })) .catch((error) => res.status(400).json({ error })); });
按照上面的步骤调整后,你的POST请求应该就能正常工作了——核心就是保证前端发送的数据格式和后端的解析方式完全匹配!
内容的提问来源于stack exchange,提问作者MDavid power's my intelligence
相关产品推荐
相关产品推荐

