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



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

反应原生代码:

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(`nnnnRESPONSE---->${JSON.stringify(response)}nnnn`)
this.setState({isLoading: false})
})
.catch((error) => {
console.log((`nnnnERROR---->${error}nnnn`))
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"}

如前面的答案所述,响应对象具有返回承诺(解析为实际数据(的.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((`nnnnERROR---->${error}nnnn`));
}
}

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

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

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

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

最新更新