How to return the json response from the fetch API(如何从 fetch API 返回 json 响应)
问题描述
我有这样的功能:
check_auth(){
fetch(Urls.check_auth(), {
credentials: 'include',
method: 'GET'
}).then(response => {
if(response.ok) return response.json();
}).then(json => {
return json.user_logged_in;
});
}
然后我尝试这样做:
if(this.check_auth()){
// do stuff
} else {
// do other stuff
}
但是,this.check_auth()
总是 undefined
.
我在这里缺少什么?我认为在 fetch 的 then()
中是 resolved Promise 对象的位置,因此我认为当用户登录时我会得到 true
在.但事实并非如此.
What am I missing here? I thought that within fetch's then()
was where the resolved Promise object was therefore I thought that I'd get true
when the user was logged in. But this is not the case.
任何帮助将不胜感激.
推荐答案
使用回调
check_auth(callback){
fetch(Urls.check_auth(), {
credentials: 'include',
method: 'GET'
}).then(response => {
if(response.ok) return response.json();
}).then(json => {
callback(json.user_logged_in);
});
}
check_auth(function(data) {
//processing the data
console.log(d);
});
在 React 中它应该更容易处理,您可以调用 fetch 并更新状态,因为每次使用 setState 更新状态时都会调用渲染方法,您可以使用状态进行渲染
In React it should be easier to handle, You can call a fetch and update the state, since on every update of state using setState the render method is called you can use the state to render
check_auth = () =>{
fetch(Urls.check_auth(), {
credentials: 'include',
method: 'GET'
}).then(response => {
if(response.ok) return response.json();
}).then(json => {
this.setState({Result: json.user_logged_in});
});
}
这篇关于如何从 fetch API 返回 json 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从 fetch API 返回 json 响应


基础教程推荐
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01