【问题标题】:React Native Fetch API - can't access json or body of response [closed]React Native Fetch API - 无法访问json或响应主体[关闭]
【发布时间】:2018-02-23 17:03:56
【问题描述】:

尝试使用 Fetch 向我的后端调用 API,但我无法访问响应正文。互联网上有很多不同的符号和语法,我不知道如何正确地做到这一点。

我已经尝试过 response.json() 和 responseJson,并且对两者都进行了字符串化。我没有得到我想要的响应的实际正文。它意味着有一个密钥/令牌,然后我保存。

responseJson 返回:responseJson:

{"_40":0,"_65":0,"_55":null,"_72":null}

这是我的功能:

export function LogIn(em, pass) {
    return (dispatch) => {

        console.log('LogIn called');
        dispatch(logInIsLoading(true));
        //from phone
        *fetch('http://192.168.1.18:8080/rest-auth/login/', {
          method: 'POST',
          headers: {
            // 'Accept': 'application/json',
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            'email': em,
            'password': pass,
          })
        }).then((response) => {
                console.log("response " + JSON.stringify(response));
                if (!response.ok) {
                    console.log("ERROR: " + response.statusText);
                    throw Error(response.statusText);
                }

                dispatch(logInIsLoading(false));

                return response;
            })
            .then((response) => {
              responseJson = response.json();
              console.log("responseJson: " + JSON.stringify(response.json()));

              return responseJson
            })
            .then((responseJson) => {

              AsyncStorage.multiSet([['key', responseJson.key], ['loggedIn', true]], () => {
                    console.log(responseJson.key);
                    dispatch(isLoggedIn(true));
                    dispatch(getKey(responseJson.key));

                });


            })*
            .catch(() => dispatch(logInHasErrored(true)));
    };
}

这是响应,但我无法找到正文中的关键:

response {"type":"default","status":200,"ok":true,"headers":{"map":
{"allow":["POST, OPTIONS"],"set-cookie":
["csrftoken=DOMxD5IhNz5Vwm9a3niAR1tRyqBfNzUqnQMAEgk7AGwtwCgnRnZo9x0AMTM2IfK
q; expires=Fri, 22-Feb-2019 17:31:58 GMT; Max-Age=31449600; Path=/, 
sessionid=er3fujv8ji96t41n1n8dlzb3zz1itwuj; expires=Fri, 09-Mar-2018 
17:31:58 GMT; httponly; Max-Age=1209600; Path=/"],"content-type":
["application/json"],"content-length":["50"],"x-frame-options":
["SAMEORIGIN"],"vary":["Accept, Cookie"],"server":["WSGIServer/0.1 
Python/2.7.14"],"date":["Fri, 23 Feb 2018 17:31:58 
GMT"]}},"url":"http://192.168.1.18:8080/rest-auth/login/","_bodyInit":"
{\"key\":\"a9951fd6abff4fed35d9a8d1c275bf1212887513\"}","_bodyText":"
{\"key\":\"a9951fd6abff4fed35d9a8d1c275bf1212887513\"}"}

【问题讨论】:

    标签: android django react-native fetch


    【解决方案1】:
    1. response.json() 返回承诺
    2. AsyncStorage.multiSet - 返回 Promise。 multiSet 的第二个参数是函数,它将被调用,并带有一个发现的任何特定于键的错误的数组
    export function LogIn(em, pass) {
        return (dispatch) => {
            console.log('LogIn called');
            dispatch(logInIsLoading(true));
            fetch('http://192.168.1.18:8080/rest-auth/login/', {
              method: 'POST',
              headers: {
                // 'Accept': 'application/json',
                'Content-Type': 'application/json',
              },
              body: JSON.stringify({
                'email': em,
                'password': pass,
              })
            }).then((response) => {
               if (!response.ok) {
                  console.log("ERROR: " + response.statusText);
                  throw Error(response.statusText);
               }
               dispatch(logInIsLoading(false));
               return response;
            })
            .then((response) => {
                  return response.json()
            })
            .then((responseJson) => {
                  console.log('responseJson', responseJson);
                  return AsyncStorage.multiSet([['key', responseJson.key],['loggedIn', true]], () => {
                        dispatch(logInHasErrored(true));
                  })
                  .then(() => {    
                      dispatch(isLoggedIn(true));
                      dispatch(getKey(responseJson.key));
                  })
            })
            .catch(() => dispatch(logInHasErrored(true)));
        };
    }
    

    【讨论】:

      【解决方案2】:

      这对于 axios 来说非常简单。 首先通过npm install --save axios安装axios

      然后在您的Component 中执行以下操作:

      handleInput = async() => {
          const res = await axios.post('http://192.168.1.18:8080/rest-auth/login/', {
             email: this.state.email,
             password: this.state.password
          });
          const data = await res.json();
          console.log(data);
      }
      

      确保您已将电子邮件和密码分别存储在this.state.emailthis.state.password 中,并在用户按下提交按钮时调用handleInput。 不要忘记导入 axios import axios from 'axios'

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-18
        • 2021-06-05
        • 2020-03-26
        • 1970-01-01
        • 1970-01-01
        • 2019-01-15
        相关资源
        最近更新 更多