【问题标题】:React-native axios method POST response.data nullReact-native axios 方法 POST response.data null
【发布时间】:2018-01-07 03:22:57
【问题描述】:

我在学校项目中使用 React-native 并使用 axios 来获取数据。 这是我的功能:

    login(username, password){

    axios({
        method : 'post',
        url : 'http://xxxx.xxxx.com/UserRestController.php',
        data : {
            accountId : 2
        }
    })
    .then(function (response) {
    console.log('data', response.data);
    })
    .catch(function (error) {
        console.log(error);
    });
}

当我尝试显示响应时,这始终为空。 像这样

      data Object {
  "config": Object {
    "adapter": [Function xhrAdapter],
    "data": "{\"accountId\":2}",
    "headers": Object {
      "Accept": "application/json, text/plain, */*",
      "Content-Type": "application/json;charset=utf-8",
    },
    "maxContentLength": -1,
    "method": "post",
    "timeout": 0,
    "transformRequest": Object {
      "0": [Function transformRequest],
    },
    "transformResponse": Object {
      "0": [Function transformResponse],
    },
    "url": "http://ariary.vola.mg/UserRestController.php",
    "validateStatus": [Function validateStatus],
    "xsrfCookieName": "XSRF-TOKEN",
    "xsrfHeaderName": "X-XSRF-TOKEN",
  },
  "data": "",
  "headers": Object {
    "access-control-allow-origin": "*",
    "connection": "keep-alive",
    "content-type": "text/html; charset=UTF-8",
    "date": "Mon, 31 Jul 2017 13:29:28 GMT",
    "server": "nginx",
    "transfer-encoding": "chunked",
    "vary": "Accept-Encoding",
    "x-powered-by": "EasyEngine 3.7.4",
  },
  "request": XMLHttpRequest {
    "DONE": 4,
    "HEADERS_RECEIVED": 2,

我在另一个函数中使用 axios.GET,效果很好。有人能帮我吗? 谢谢

【问题讨论】:

  • 谢谢,如何删除它们?

标签: post mobile react-native axios


【解决方案1】:

在访问它的数据之前尝试解析对 json 的响应:

axios({
    method : 'post',
    url : 'http://xxxx.xxxx.com/UserRestController.php',
    data : {
        accountId : 2
    }
})
.then((res) => res.json())
.then(function (response) {
console.log('data', response.data);
})
.catch(function (error) {
    console.log(error);
});

【讨论】:

  • 感谢您的回复,但是当我按照您的说法尝试时出现此错误。 [TypeError: undefined is not a function (evalating 'res.json()')]
【解决方案2】:

经过一些测试,我的问题不是响应而是我的数据。这始终为空。 accountId 在我的服务器中未定义。但我不知道为什么?

【讨论】:

  • 可能有几个选项:添加正确的标题,如“接受:应用程序/json”。或使用 JSON.stringify() 将您发送的数据中的 json 解析为字符串
猜你喜欢
  • 2019-05-18
  • 2019-08-09
  • 2022-01-11
  • 1970-01-01
  • 2019-02-27
  • 2019-04-07
  • 1970-01-01
  • 1970-01-01
  • 2018-10-01
相关资源
最近更新 更多