Javascript 如何使用fetch()api的响应
如何使用fetch api的响应 我尝试Javascript 如何使用fetch()api的响应,javascript,typescript,fetch,Javascript,Typescript,Fetch,如何使用fetch api的响应 我尝试返回我的响应,但当我尝试在函数中打印此值时,我得到了未定义的, 有人能告诉我如何在不同的功能中使用这个响应吗 我的响应是嵌套对象的json async fetchData() { const url = `...`; fetch(url, { method: 'post', headers: { 'Accept': 'application/json',
返回
我的响应,但当我尝试在函数中打印此值时,我得到了未定义的
,
有人能告诉我如何在不同的功能中使用这个响应吗
我的响应是嵌套对象的json
async fetchData() {
const url = `...`;
fetch(url, {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
//
})
}).then((response) => response.json())
.then(response => {;
console.log(response) //correct response
return response;
})
}
async getDataFromFetchApi() {
const data= await this.fetchData();
console.log(data); // undefined
if(data != undefined){
throw new BadRequestException();
}
return data;
}
感谢您的帮助您必须返回
fetchData
函数范围内的数据:
async fetchData(){
常量url=`…`;
const response=等待获取(url{
方法:“post”,
标题:{
“接受”:“应用程序/json”,
“内容类型”:“应用程序/json”
},
正文:JSON.stringify({
//...
})
});
返回响应;
}
归根结底,异步
函数必须返回正确工作的承诺<代码>获取数据
没有返回值。返回响应
位于.then
内部,不适用于获取数据
函数本身
对于上述代码,最少的修改只是在fetchData
函数中返回fetch(…)
,如下所示:
async fetchData() {
const url = `...`;
return fetch(/* ... */)
.then((response) => response.json())
.then(response => {
console.log(response) //correct response
return response;
})
}
async fetchData() {
const url = `...`;
const resp = await fetch(/* ... */);
const json = await resp.json();
console.log(json);
return json;
}
或者,您可以尽可能使用async/await
语法,并摆脱。然后
s,如下所示:
async fetchData() {
const url = `...`;
return fetch(/* ... */)
.then((response) => response.json())
.then(response => {
console.log(response) //correct response
return response;
})
}
async fetchData() {
const url = `...`;
const resp = await fetch(/* ... */);
const json = await resp.json();
console.log(json);
return json;
}
这回答了你的问题吗?