使用fetch react native时获得不同的JSON响应

htrmnn0y  于 2023-11-20  发布在  React
关注(0)|答案(3)|浏览(124)

我有一个react应用程序,当用户点击登录时,它会调用一个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})
    })
}

字符串
控制台响应:
响应->{"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,Excell-Control-Allow-Headers,Origin,Accept,X-Requested-With,Content-Type,Excell-Control-Request-Method,请输入您的电子邮件地址,然后点击" http://www.example.com",然后点击" http://www.example.com"。abc.com
预期的API响应:
RESPONSE->{"message ":" Auth Fail "}

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


RESPONSE->{"message ":" Auth验证"}

gblwokeq

gblwokeq1#

正如前面的答案所指出的,响应对象有一个.json()函数,它返回一个promise(解析为实际数据)。
此外,您还可以使用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`));
  }
}

字符串

fiei3ece

fiei3ece2#

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

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

字符串

w7t8yxp5

w7t8yxp53#

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

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

字符串

相关问题