Javascript React和节点登录实现
我有一个需要进行身份验证的应用程序 我制作了react路由器auth workflow()的精确副本 Auth.jsJavascript React和节点登录实现,javascript,node.js,reactjs,react-router,mern,Javascript,Node.js,Reactjs,React Router,Mern,我有一个需要进行身份验证的应用程序 我制作了react路由器auth workflow()的精确副本 Auth.js const auth = { isAuthenticated: false, authenticate(data, scb, fcb) { fetch("/api/login", { method: "POST", headers: { "Content-Type": "application/json; charset=utf-8" },
const auth = {
isAuthenticated: false,
authenticate(data, scb, fcb) {
fetch("/api/login", {
method: "POST",
headers: {
"Content-Type": "application/json; charset=utf-8"
},
body: JSON.stringify(data)
})
.then(res => res.json())
.then(res => {
console.log(res);
localStorage.setItem("token", res.token);
this.isAuthenticated = true;
scb();
})
.catch(ex => {
this.isAuthenticated = false;
fcb();
});
},
signout(cb) {
localStorage.removeItem("token");
this.isAuthenticated = false;
cb();
},
checkSignIn(cb, fcb) {
fetch("api/user/me", {
headers: {
"content-type": "application/json",
"x-auth-token": localStorage.token
}
})
.then(res => res.json())
.then(res => {
console.log("here");
this.isAuthenticated = true;
cb();
})
.catch(err => {
console.log("here in checksign in catch");
this.isAuthenticated = false;
fcb();
});
}
};
export default auth;
现在,当页面加载时,我使用checkSignIn方法,如果用户经过身份验证,则将用户重定向到仪表板
主要问题是如果令牌过期,我的API调用将被拒绝,现在我想将用户重定向回登录,我使用signout方法并传递回调来更改组件的状态并返回,但问题是我看到代码中重复太多,在每次api调用中,如果api调用失败,或者我必须使用withRouter(HOC),我必须通过回调来更改页面的状态,但我必须将我的每个组件包装在其中。
是否有其他方法实现此功能但回调始终是相同的,对吗?(
如果(userToken已过期){注销用户并将其发送回主页}
)您可以通过一个公共HTTP模块或函数抽象所有API调用,该模块或函数始终将该测试应用于每个调用。然后,无论您使用的是哪种API,如果您的令牌过期,包装器都会将用户发送到他们需要去的地方。因此,我将创建一个模块来进行所有API调用,但我认为在调用该函数时,我必须提供重复的回调