Discord Bot中Fetch API的PUT请求报错404,求问题排查
Discord Bot开发:嵌套JSON结构下Fetch PUT请求404错误问题
开发Discord Bot时遇到如下问题:使用Fetch API发起PUT请求时返回404错误,但操作无嵌套结构的普通JSON文件时,PUT请求可正常执行。尝试修改嵌套JSON中的server字段后发送PUT请求始终失败,该问题已困扰三天。
可正常运行的代码
JSON(后端接收格式)
{ "id": 1, "title": "How to Use Fetch to Make GET Requests in React", "content": "In this blog post, we will learn how to use the Fetch API to make GET requests in React...", "author": "David", "date": "2023-01-01" }
JavaScript请求代码
const data = { title: "How to Use Fetch to Make PUT Requests in React", content: "In this blog post, we will learn how to use the Fetch API to make PUT requests in React..." }; const requestOptions = { method: "PUT", // 指定请求方法 headers: { "Content-Type": "application/json" }, // 指定内容类型 body: JSON.stringify(data) // 以JSON格式发送数据 }; // 发起请求 fetch("http://localhost:3000/economy", requestOptions) .then(response => response.json()) // 将响应解析为JSON .then(data => console.log(data)) // 处理返回的数据 .catch(error => console.error(error)); // 处理错误
尝试的嵌套结构修改代码
JavaScript请求代码
fetch("http://localhost:3000/economy") .then(economy => economy.json()) .then(test1 => { let gettur = test1[0].op[0].server let edit = (test1[0].op[0].server = "Bubalo"); console.log(edit); const respond = fetch("http://localhost:3000/economy", { method: "PUT", headers: { Accept: "application/json", "Content-Type": "application/json", }, body: JSON.stringify(edit), }) .then (response=>console.log(response)) console.log(gettur); });
对应的嵌套JSON结构
{ "economy": [ { "op": [ { "server": "1089497578141388920", "users": [ { "id": "950379710284718111", "cash": 200, "bank": 300 }, { "id": "768486511531393024", "cash": 0, "bank": 2000 } ] }, { "server": "1089497578141388720", "users": [ { "id": "950379710284718111", "cash": 200, "bank": 300 }, { "id": "768486511531393024", "cash": 0, "bank": 2000 } ] } ], "id": "5b91" } ] }
错误信息
PUT请求返回404状态码
问题原因及解决方案
核心问题:请求体格式不匹配
你当前的PUT请求只传递了单个字符串"Bubalo",但后端期望接收的是和原有数据一致的完整嵌套JSON结构。之前正常的请求是传递包含对应字段的对象,和后端接受格式匹配;而现在edit变量是test1[0].op[0].server = "Bubalo"的赋值结果(即字符串),导致请求体格式完全不符合后端要求,后端无法匹配到对应的处理路由,因此返回404。修正后的代码
修改嵌套字段后,需要将完整的修改后的数据结构作为请求体发送:
fetch("http://localhost:3000/economy") .then(economy => economy.json()) .then(test1 => { // 修改目标server字段 test1[0].op[0].server = "Bubalo"; fetch("http://localhost:3000/economy", { method: "PUT", headers: { Accept: "application/json", "Content-Type": "application/json", }, // 传递完整的修改后的数据结构 body: JSON.stringify(test1), }) .then(response => { // 检查响应状态是否正常 if (!response.ok) throw new Error(`请求失败,状态码:${response.status}`); return response.json(); }) .then(data => console.log("修改成功:", data)) .catch(error => console.error("请求出错:", error)); });
- 额外排查点
- 确认后端
/economy路由的PUT请求处理逻辑,是否支持接收完整的嵌套JSON结构。 - 检查GET请求返回的
test1结构是否和后端期望的PUT请求体结构完全一致,避免修改时破坏了原有数据结构。
- 确认后端
内容的提问来源于stack exchange,提问作者Mapahce2212
相关产品推荐
相关产品推荐

