React Native“fetch”返回没有信息的服务器响应

时间:2018-04-30 02:04:01

标签: javascript http react-native

我正在使用react native创建一个应用程序来充当当前存在的网站(具有在手机上工作的用户界面)。我正在使用“fetch”方法发送Http POST请求以从Web服务器获取信息。 Web服务器发送响应但不包含响应消息: enter image description here

我道歉这是一张图片,但调试器对我不起作用。 用于发送请求的代码:

HttpRequest = (RequestURL, callback) => {

    var AdminLoginBindingModel = {
      usr: this.state.username,
      pwd: this.state.password,
    }

    fetch(RequestURL,
    {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },     
      body: JSON.stringify(AdminLoginBindingModel)
    })
    .then((res) => {
      callback(res);
    })
    .catch((error) => {
      this.setState({Response: "Error: " + error});
    })                       
}

参数中的回调函数只是一个更改状态变量以在屏幕上显示信息的函数

ValidateResponse(response){
    this.setState({Response: "Result: " + JSON.stringify(response), 
        displayMessage: "Success"});
    console.log(JSON.stringify(response));
}

发送的请求是“https://mibase-test.mibase.com.au/members/api/startSession.php?usr=&pwd=” 无论登录是否正确,服务器都会使用json对象进行响应

编辑: 将响应更改为

.then((res) => {
      callback(res.json());
})

结果: enter image description here

2 个答案:

答案 0 :(得分:2)

要从获取响应中获取对象,您必须像下面这样调用res.json

fetch(RequestURL, {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },     
  body: JSON.stringify(AdminLoginBindingModel)
})
.then(res => res.json())    // HERE
.then(obj => callback(obj))

但它发生错误,因为响应主体本身是无效的json格式。它包含一些HTML标记:

{"member": {"username":"","password":"","key":"***","status":"No"}}<br><br>Username: <br>Key: ***

请检查服务器的实施情况。

编辑:完整代码

const fetch = require("node-fetch")

HttpRequest = (RequestURL, callback) => {
    const AdminLoginBindingModel = { usr: "foo", pwd: "bar" }
    fetch(RequestURL, {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },     
      body: JSON.stringify(AdminLoginBindingModel)
    })
    .then(res => res.json())
    .then(obj => callback(obj))
    .catch(error => console.log(error))                       
}

const ValidateResponse = response => console.log(JSON.stringify(response))
URL = 'https://mibase-test.mibase.com.au/members/api/startSession.php?usr=&pwd='
HttpRequest(URL, ValidateResponse)

答案 1 :(得分:1)

response不直接包含收到的数据。它提供了检索它的接口方法。例如,使用response.json()将响应文本解析为JSON。它将返回解析为已解析对象的promise。您不需要在其上拨打JSON.parse

fetch(RequestURL,
{
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },     
  body: JSON.stringify(AdminLoginBindingModel)
})
.then((res) => {
  return res.json();
}).then((obj) => {
  console.log(obj);
});

检查https://developer.mozilla.org/en-US/docs/Web/API/Responsehttps://facebook.github.io/react-native/docs/network.html以获取更多信息。