【问题标题】:Fetch API: PUT request for JSON returning 404 while GET is working properlyFetch API:当 GET 正常工作时,对 JSON 的 PUT 请求返回 404
【发布时间】:2021-05-09 05:34:32
【问题描述】:

我有 1 个 json 文件:{ "clicks": 0 }

我正在尝试从中检索数据,然后对其进行更新。 GET 有效,但 PUT 无效。

我使用 Typescript,这应该不是问题:

  const getClickCounterJsonData = () => fetch(
    'click-counter.json',
    {
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
    }
  )
    .then(response => response.json())
    .then(myJson => myJson);

  // this call is actually added to onClick, but you get the idea
  getClickCounterJsonData().then(data => console.log(data['clicks'])); //this works, returns the actual value of the clicks property

现在不工作的更新功能:

      const updateClickCounterJsonData = (newData: any) => fetch(
        'click-counter.json',
        {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
          },
          body: JSON.stringify(newData)
        }
      )
        .then(response => response.json())
        .then(myJson => myJson);

    // again in a onClick function
    updateClickCounterJsonData({ clicks: 5 }).catch(error => console.log(error)); // this returns SyntaxError: Unexpected token < in JSON at position 0
   // and also the request in the Network tab says 404 Not Found with a preview text: Cannot PUT click-counter.json

我不允许对 json 资源执行 PUT 请求吗?我对这个话题不是很熟悉,但是发现了很多资源,这应该是可能的。 GET 按预期工作,PUT 似乎配置得很好,但我不知道为什么它不起作用。

我错过了什么吗?

【问题讨论】:

标签: javascript typescript fetch-api


【解决方案1】:

服务器可以根据 HTTP 请求类型路由请求 - 例如 express/node.js 服务器提供显式方法来处理 PUT、POST 和 GET 请求,分别使用 app.putapp.postapp.get。其逻辑属于“请求路由”的范畴。如果没有遇到与请求模式匹配的路由,则路由器通常被编码为通过服务器代码响应404 错误。

因此,您不能只将有效的 GET 请求更改为 PUT 请求并期望服务器适应 - 它需要更改代码才能这样做。

【讨论】:

  • 我明白了。好的,谢谢回复!我会坚持使用 MongoDB 或 Redis。显然,我试图重新发明热水以获得更简单/更快的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-02
  • 1970-01-01
  • 2015-11-14
  • 2018-05-05
  • 2018-09-04
  • 1970-01-01
相关资源
最近更新 更多