如何通过fetch POST向json-server数据库嵌套字段添加数据
问题解决说明
核心原因
json-server默认要求顶级资源字段对应数组结构,才能通过/资源名/ID的路径直接访问子项。你当前的db.json中users字段对应的值是对象而非数组,所以访问http://localhost:3000/users/sarahedo会返回空对象。
解决步骤
第一步:调整db结构(适配json-server默认规则)
将db.json修改为如下格式,把users改为数组结构,每个用户作为数组的元素:
{ "users": [ { "id": "sarahedo", "name": "Sarah Edo", "avatarURL": "https://pluralsight.imgix.net/author/lg/6f77d113-ea36-4592-814d-9d4acb32f231.jpg", "answers": { "8xf0y6ziyjabvozdd253nd": "optionOne", "6ni6ok3ym7mf1p33lnez": "optionOne", "am8ehyc8byjqgar0jgpub9": "optionTwo", "loxhs1bqm25b708cmbf3g": "optionTwo" }, "questions": ["8xf0y6ziyjabvozdd253nd", "am8ehyc8byjqgar0jgpub9"] } ] }
修改后重启json-server,此时访问http://localhost:3000/users/sarahedo即可正常返回用户数据。
第二步:更新questions数组
更新现有资源的局部字段推荐使用PATCH请求(语义更匹配),fetch写法如下:
// 要新增的问题ID const newQuestionId = "your_new_question_id"; // 先查询当前用户的questions数组,拼接新ID后提交更新 fetch("http://localhost:3000/users/sarahedo") .then(res => res.json()) .then(user => { return fetch("http://localhost:3000/users/sarahedo", { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ questions: [...user.questions, newQuestionId] }) }) }) .then(res => res.json()) .then(updatedUser => console.log("更新完成", updatedUser))
如果你必须使用POST请求实现该需求,需要额外配置json-server的自定义中间件拦截POST请求做更新逻辑,成本较高,不推荐。
内容的提问来源于stack exchange,提问作者Bassel Turky
相关产品推荐
相关产品推荐

