【问题标题】:Unable to perform POST request with fetch in react native无法在本机反应中使用 fetch 执行 POST 请求
【发布时间】:2017-12-02 08:50:34
【问题描述】:

我正在尝试对节点中的 json-server 提供的 json 文件执行 POST 操作。我在尝试执行上述 POST 操作时收到以下 500 错误:

"TypeError: 无法读取未定义的属性 'id' 在 Function.createId"

post操作如下:

pushState = () => {
        var update = {
            "a": 1,
            "b": 2
        };

    return fetch(url, {
      mode: 'cors',
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(update)
    })
    .then((response) => {
      console.log(response);
      response.text();
    })
    .then((responseData) => {
      console.log("Response:",responseData);
    }).catch((error) => {
      console.log(error);
    })
    .done();
  }

我是否正确地执行了 POST 请求?

编辑:添加异步和等待后,我仍然收到相同的错误:

pushState = async () => {
  var update = {
    "a": 1,
    "b": 2
  };

  var result = await fetch(url, {
    mode: 'cors',
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(update)
  })
  .then((response) => {
    console.log(response);
    return response;
  })
  .catch((error) => {
    console.log(error);
  });

  return result;
}

【问题讨论】:

  • 我认为这可能是服务器问题,尝试通过更新传递 id? var update = { id: 1, a: 1, b: 2 };
  • 添加和 ID 字段有效!是否有需要 id 字段的原因?如果我调用的 API 没有 id 字段,或者有不同名称的 ID 字段怎么办?
  • 我相信这只是因为您使用的是 json-server 并且设置的方式是寻找一个 id,这就是为什么它说“TypeError: Cannot read property 'id' of undefined在 Function.createId”。并非所有 API 都需要 id,但使用 id 更好地跟踪数据是一种很好的做法。

标签: javascript json react-native fetch json-server


【解决方案1】:

这里有两个问题:

  1. 你没有从fetch返回任何东西。
  2. fetch 是异步的。以您现在使用pushState 立即返回结果的方式调用它,当您遇到错误时,它几乎总是会返回undefined。您需要使用 async/await 写入 pushState

编辑回答 cmets:

由于您使用的是函数箭头语法,因此使 pushState 异步将如下所示:

pushState = async () => { /* code */ }

为了帮助您了解fetch 的工作原理,我建议您阅读this first。然后要从高层次理解 async/await,请阅读 this article。您生成的代码将如下所示:

pushState = async () => {
  var update = {
    "a": 1,
    "b": 2
  };

  var result = await fetch(...) // Remember to return something.

  return result;
}

【讨论】:

  • 所以我将其设为“async pushState()”,对吗?我将如何使用 await?
  • @BillyBobJoel 编辑希望能回答您的问题。
  • 我已经添加了更新的代码。我仍然遇到同样的错误。问题可能出在我提供 json 文件的方式上吗?
  • @BillyBobJoel 也许吧。可能是 Matt Aft 所建议的。您要发布到的url 是什么?您的 json-server 数据库是什么样的?
猜你喜欢
  • 2016-11-28
  • 1970-01-01
  • 2020-06-07
  • 1970-01-01
  • 1970-01-01
  • 2015-11-28
  • 2019-02-09
  • 2020-12-24
  • 2019-08-02
相关资源
最近更新 更多