javascript - JSON 服务器 - 将数据发布到数组中的特定对象中

标签 javascript reactjs post fetch react-hooks

我正在练习 fetch api,但在发布数据时遇到问题...第一步,我发布到“http://localhost:3003/users” ' 并且工作正常 -> 代码:

(async () => {
        const res = await fetch('http://localhost:3003/users', {
          method: 'POST',
          body: JSON.stringify({ name, password }),
          headers: {
            'Content-Type': 'application/json'
          }
        });

但在另一个组件(第二步)中我有以下代码:

  useEffect(() => {
    (async () => {
      try {
        const resp = await fetch(`http://localhost:3003/users/${userID}`, {
          method: 'POST',
          body: JSON.stringify({ tasks: [1, 2, 3] }),
          headers: {
            'Content-Type': 'application/json'
          }
        }).then(res => console.log(res));
      } catch (err) {
        console.error(err);
      }
    })();
  }, [userID]);

登录到控制台后,得到:

Response {type: "cors", url: "http://localhost:3003/users/0", redirected: false, status: 404, ok: false, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: false
redirected: false
status: 404
statusText: "Not Found"
type: "cors"
url: "http://localhost:3003/users/0"

但是当我去http://localhost:3003/users/0时,我可以看到用户,所以看起来 url 有效...当然,当我删除 ${userID} 时它有效,但数组被添加为最后一个对象,而不是添加到该特定用户...更重要的是 - http://localhost:3003/users/ ${userID} 使用 GET 方法。

问题是 - 如何将数据发送到 JSON 服务器中数组中的单个对象?

db.json:

{
  "users": [
    {
      "id": 0,
      "name": "Ola",
      "password": "12345"
    },
    {
      "name": "newuser",
      "password": "newuser",
      "id": 1
    }
  ]
}

表单提交检查是否存在具有该名称的用户;如果没有,请发布新用户

最佳答案

已解决

我使用了错误的方法 - POST 而不是 PATCH

关于javascript - JSON 服务器 - 将数据发布到数组中的特定对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59580493/

相关文章:

php - 在加载网页时向用户显示消息

javascript - 功能适用于移动Safari

reactjs - react native 数据类型

c# - WebBrowser 控件忽略来自 POST 请求的 302 重定向?

jquery - 从 jQuery 到 Spring boot MVC 的 POST 需要用户凭据

javascript - 将数据发布到服务器 Angular $http post

javascript - 如何更改面板内 anchor 标记的样式属性?

Javascript 热图 ReferenceError h337.create

reactjs - 我可以在不双击 React JS 的情况下编辑 MUI 数据网格单元格吗?

reactjs - 使用 Typescript 进行 Redux reducer 初始状态