我是React-native的新手,我正在向服务器发送请求,并希望在同一块中获取响应和正文,以便可以将两个项目都发送到我的提取方法看起来像的另一个函数中
send_request = (data) =>{
url = BASE_URL + "some/url.json"
fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
user: {
email: data.email,
full_name: data.name,
}
})
}).then((response) => {
//how can I get response body here so that I can call following method
// this.use_response(responsebody, response.headers)
return response.json()
}).then((responseJson) => {
// or how can I get response headers here so that I can call following fuction
// this.use_response(responseJson, headers)
return responseJson
}).catch((error) => {
console.log(error)
});
}
我如何一次使用两者,请先帮助谢谢!
答案 0 :(得分:3)
response.headers
是一个可用的对象,而request.json()
是需要解决的承诺。
为了使用ES6的简单承诺将它们放在一个地方,应该嵌套then
:
...
.then((response) => {
return response.json().then(responseJson => {
this.use_response(responseJson, response.headers)
});
})
或者多个值应作为数组或对象一起通过链传递:
...
.then((response) => {
return Promise.all([response.json(), response.headers]);
}).then(([responseJson, headers]) => {
this.use_response(responseJson, headers)
})
或者由于React应用程序不限于ES5 / ES6并且可以使用Babel支持的所有功能,因此可以使用async..await
来自然解决此类问题:
send_request = async (data) =>{
url = BASE_URL + "some/url.json"
const response = await fetch(url, {...})
const responseJson = await response.json();
this.use_response(responseJson, response.headers);
}
答案 1 :(得分:1)
我看到的最简单的方法是将标头发送到send_request
函数,并在收到响应后将它们包装到一个对象中并返回它们。