Reactjs 检查用户是否已登录React Js
大家好,我在react项目中有一个JWT身份验证,我想做一个函数来检查用户是否登录。我的登录功能如下:Reactjs 检查用户是否已登录React Js,reactjs,Reactjs,大家好,我在react项目中有一个JWT身份验证,我想做一个函数来检查用户是否登录。我的登录功能如下: export function login(data) { const endpoint = '/api/auth/jwt/' const csrfToken = cookie.load('csrftoken') let thisComp = this if (csrfToken !== undefined) { let lookupOptions
export function login(data) {
const endpoint = '/api/auth/jwt/'
const csrfToken = cookie.load('csrftoken')
let thisComp = this
if (csrfToken !== undefined) {
let lookupOptions = {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data),
credentials: 'include'
}
fetch(endpoint, lookupOptions)
.then(function(response){
return response.json()
}).then(function(responseData){
console.log(responseData)
localStorage.token = responseData.token
localStorage.expires = responseData.expires // Store the token
console.log("Token Stored", localStorage.token)
console.log("Token Expires", responseData.expires)
refreshToken(data) // Put in to the refresh function
}).catch(function(error){
console.log("error", error)
})
}
}
export function isLoggedIn() {
// Check if we have a token stored
if (localStorage.token !== undefined) {
// I also want to check if the token is still work and don't expire
// i have acces to the expiration date like this :
// localStorage.token == > Token Expires 2018-06-19T14:51:59.451703Z in
the console
// How can check if the token still work ?
return true
}
return false
}
我的函数是这样的:
export function login(data) {
const endpoint = '/api/auth/jwt/'
const csrfToken = cookie.load('csrftoken')
let thisComp = this
if (csrfToken !== undefined) {
let lookupOptions = {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data),
credentials: 'include'
}
fetch(endpoint, lookupOptions)
.then(function(response){
return response.json()
}).then(function(responseData){
console.log(responseData)
localStorage.token = responseData.token
localStorage.expires = responseData.expires // Store the token
console.log("Token Stored", localStorage.token)
console.log("Token Expires", responseData.expires)
refreshToken(data) // Put in to the refresh function
}).catch(function(error){
console.log("error", error)
})
}
}
export function isLoggedIn() {
// Check if we have a token stored
if (localStorage.token !== undefined) {
// I also want to check if the token is still work and don't expire
// i have acces to the expiration date like this :
// localStorage.token == > Token Expires 2018-06-19T14:51:59.451703Z in
the console
// How can check if the token still work ?
return true
}
return false
}
您不能检查存储在本地存储中的expires属性并将其与当前日期进行比较吗 其他处理方法:将过期日期存储在令牌本身中,然后使用jwt解码库对令牌进行解码并从中提取。如果您使用的是刷新令牌,您只需等待服务器返回401未经授权的响应,然后发送刷新令牌以请求新的响应