首页 > 解决方案 > 为什么 Simple axios 不适用于 React Native

问题描述

我正在尝试在 React Native、Expo android 客户端上使用 axios 获取数据。我写:

axios({
    url: 'http://my_local_id/graphql',
    method: 'get',
    data: {
      query: `
      query allPosts {
        posts(listType: "all") {
          text
        }
       }
      `,
    }
  }).then(result => {
    console.log(result.data);
  }).catch(function (error) {
    console.log(error);
    console.log(error.request._response);
  });

该错误给了我一个日志:“请求失败,状态码为 400”和一些其他消息

堆栈跟踪:node_modules\axios\lib\core\createError.js:16:24 in createError node_modules\axios\lib\core\settle.js:19:6 在结算 node_modules\axios\lib\adapters\xhr.js:77 :13 在 handleLoad node_modules\event-target-shim\lib\event-target.js:172:43 在 dispatchEvent node_modules\react-native\Libraries\Network\XMLHttpRequest.js:570:23 在 setReadyState node_modules\react-native\ Libraries\Network\XMLHttpRequest.js:392:25 in __didCompleteResponse node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:191:12 在发出 node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:349: 47 在 __callFunction node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:106:26 在 node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:297:10 in __guard node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:105:17 in callFunctionReturnFlushedQueue [native code]:null in callFunctionReturnFlushedQueue

我查看了来自 error.request._response 的消息,它显示“消息”:“POST 正文发送了无效的 JSON。” 但我只发送了一个“获取”请求。我不知道这里有什么问题。下面是我的 package.json 文件。

"axios": "^0.18.0",
 "expo": "^32.0.0",
 "react": "16.5.0",
"react-native": "https://github.com/expo/react-native/archive/sdk-32.0.0.tar.gz",

标签: reactjsreact-nativegraphqlaxios

解决方案


推荐阅读