每个下一个帖子调用都没有主体

时间:2019-02-20 14:26:52

标签: react-native axios expo

我有以下问题:

每个下一个POST调用都会收到错误:网络错误

例如,我启动应用程序,然后单击“订阅”按钮,然后发送POST呼叫并获得响应,一切正常。但是然后我单击“取消订阅”,它还会发送另一个POST调用,但是这次我遇到了网络错误。

后端家伙告诉我,没有请求的主体,请求已中止。如果我要多次单击按钮,那么所有这些请求都将无法正常工作。

如果我重新启动应用程序或等待几分钟,则第一次发布工作,但之后不会发布

我在expo中使用react-native

这是我的发布方法:

 export const apiPost = (endpoint, token, data) => {
  return new Promise((resolve, reject) => {
    axios({
      method: 'post',
      url: BASE_URL + endpoint,
      headers: {
        'content-type': 'application/json',
        'authorization': token
      },
      data: data
    }).then(res => resolve(res.data))
      .catch(err => reject(err))
 });
}

万一有人想知道这是传递给POST的数据的样子

const data = {
  name: "Some value"
}

这是我的package.json

"dependencies": {
  "@expo/samples": "2.1.1",
  "axios": "^0.18.0",
  "expo": "^30.0.0",
  "moment": "^2.24.0",
  "react": "16.3.1",
  "react-native": "https://github.com/expo/react-native/archive/sdk-30.0.0.tar.gz",
  "react-native-camera": "^1.2.0",
  "react-native-collapsible": "^1.3.0",
  "react-native-custom-picker": "^0.3.1",
  "react-native-datepicker": "^1.7.2",
  "react-native-keyboard-aware-scroll-view": "^0.7.2",
  "react-native-qrcode-svg": "^5.1.1",
  "react-native-root-toast": "^3.0.2",
  "react-native-search-filter": "^0.1.4",
  "react-native-segmented-control-tab": "^3.3.1",
  "react-native-simple-dialogs": "^1.1.0",
  "react-native-simple-radio-button": "^2.7.3",
  "react-native-svg": "^6.5.2",
  "react-native-svg-charts": "^5.2.0",
  "react-native-tab-view": "^1.0.2",
  "react-navigation": "^2.9.3",
  "react-redux": "^5.1.0",
  "redux": "^4.0.1",
  "redux-thunk": "^2.3.0",
  "socket.io-client": "2.0.4",
  "whatwg-fetch": "^2.0.4"

更新

我做了一个测试功能来向https://reqres.in/发出POST请求,即使在许多请求上,它也可以正常工作。所以我想后端提供了一个问题。尽管后端在Angular应用中可以正常运行

更新2

问题出在后端的http2上。看到这里:React-native POST request in android over https return network error

1 个答案:

答案 0 :(得分:0)

这可能是由于您返回的Promise可能需要在实际的调用函数中使用(尽管不确定)。

尝试使用 async ... await 进行操作,这要简单得多

Guid: 35918bc9-196d-40ea-9779-889d79b753f0
=> Result: C9 8B 91 35 6D 19 EA 40 97 79 88 9D 79 B7 53 F0

这是React中的CodeSandBox解决方案(以防将来删除)-

export const apiPost = async (endpoint, token, data) => {
  const data = {
    name: "Some value"
  };
  try {
      const res = await axios({
          method: 'post',
          url: BASE_URL + endpoint,
          headers: {
              'content-type': 'application/json',
              'authorization': token
          },
          data
      });
      return res.json();
  }
  catch(err) {
    console.error(err);
    return err.message;
  }
}