【问题标题】:Getting different json response when using fetch react native使用 fetch react native 时获得不同的 json 响应
【发布时间】:2018-09-27 18:21:30
【问题描述】:

我有一个反应应用程序,它在用户单击登录时调用 API。但是,react native 收到的响应与预期的响应不同。

React Native 代码:

login() {
    this.setState({isLoading: true})
    return fetch(process.env.API_USER + "/signin", {
        method: "POST", 
        headers: {
            Accept: "application/json", 
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            username: this.state.username, 
            password: this.state.password
        })
    }).then((response) => {
        console.log(`\n\n\n\nRESPONSE---->${JSON.stringify(response)}\n\n\n\n`)
        this.setState({isLoading: false})
    })
    .catch((error) => {
        console.log((`\n\n\n\nERROR---->${error}\n\n\n\n`))
        this.setState({isLoading: false})
    })
}

控制台响应:

RESPONSE---->{"type":"default","status":401,"ok":false,"headers":{"map":{"via":"1.1 vegur","date":"Thu, 27 Sep 2018 18:10:42 GMT","server":"Cowboy","etag":"W/\"17-wIxJlIRlPQbTEtBjbmLpTqPMWNo\"","connection":"keep-alive","cache-control":"public, max-age=0","x-powered-by":"Express","content-length":"23","access-control-allow-credentials":"true","access-control-allow-origin":"*","access-control-allow-methods":"*","access-control-allow-headers":"Origin, Accept,Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers","content-type":"application/json; charset=utf-8"}},"url":"abc.com","_bodyInit":{"_data":{"size":23,"offset":0,"blobId":"f4012672-62b8-4b52-be6f-06446874981c"}},"_bodyBlob":{"_data":{"size":23,"offset":0,"blobId":"f4012672-62b8-4b52-be6f-06446874981c"}}}

预期的 API 响应:

RESPONSE---->{"message": "Auth Fail"}

// ----------OR---------- //

RESPONSE---->{"message": "Auth Successfull"}

【问题讨论】:

    标签: javascript json api react-native fetch


    【解决方案1】:

    正如前面的答案所指出的,响应对象有一个.json() 函数,该函数返回一个承诺(解析为实际数据)。

    您还可以使用async/await更好地构造代码

    login = async () => {
      const options = {
        method: "POST",
        headers: {
          Accept: "application/json", 
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          username: this.state.username, 
          password: this.state.password
        }),
      };
      this.setState({isLoading: true});
    
      try {
        const response = await fetch(`${process.env.API_USER}/signin`, options);
        const responseData = await response.json(); // This is what you're missing
    
        this.setState({isLoading: false});
      } catch (error) {
        // Do something about the error
        console.log((`\n\n\n\nERROR---->${error}\n\n\n\n`));
      }
    }
    

    【讨论】:

    • 非常感谢!我已经处理这个问题很长时间了。感谢您解决它!完美运行!
    • 如果你不介意,我这里还有一个 react native 的问题:stackoverflow.com/q/52872893/10387115。如果你能看一看,那将意味着很多。提前致谢!
    【解决方案2】:

    在文档中定义的获取请求的基本结构here。从文档中,你可以试试这个

      .then((response) => response.json())
            .then((resJSON) => {
               console(resJSON);
               this.setState({isLoading: false})
            })
            .catch((error) => {
               console.log(error)
               this.setState({isLoading: false})
            })
    

    【讨论】:

      【解决方案3】:

      您需要另一个.then 来解析响应并将其转换为 JSON:

      .then(response => response.json())
      .then(data => {
          // now you can get your server response
          console.log(data)
       })    
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-03-14
        • 2017-02-07
        • 2023-03-18
        • 1970-01-01
        • 1970-01-01
        • 2016-04-28
        • 1970-01-01
        相关资源
        最近更新 更多