我的應用基于 React-admin 教程和 loopback 4 作為后端
我正在嘗試獲取登錄用戶的 id,登錄機制運行良好,但是當我嘗試訪問登錄用戶的 id 時,它仍然未定義。
在我的 authProvider 中,我的登錄功能是
login: ({ username, password }) => {
const request = new Request(
process.env.REACT_APP_API_URL '/users/login',
{
method: 'POST',
body: JSON.stringify({ email: username, password }),
headers: new Headers({ 'Content-Type': 'application/json' }),
},
);
return fetch(request)
.then((response) => {
if (response.status < 200 || response.status >= 300) {
throw new Error(response.statusText);
}
return response.json();
})
.then((auth) => {
localStorage.setItem(
'auth',
JSON.stringify({ ...auth, fullName: username }),
);
})
.catch(() => {
throw new Error('Network error');
});
},
我在一個組件中使用它:
const CurrentUserId = ({ id }) => {
const { identity, isLoading: identityLoading } = useGetIdentity();
console.log(identity);
if (identityLoading) {
return <span>Loading...</span>;
} else {
// find the user_id from the identity
const user_email = identity.fullName;
const user_id = identity.id;
return <span>id: {user_id}</span>;
}
};
但我 console.log 回傳
{id: undefined, fullName: '[email protected]', avatar: undefined}
我按照此處提供的說明進行操作 https://marmelab.com/react-admin/AuthProviderWriting.html https://marmelab.com/react-admin/useGetIdentity.html
任何想法如何檢索ID?
多謝
uj5u.com熱心網友回復:
如果您從服務器接收到 JWT 令牌,則需要對其進行解碼并像這樣存盤它:
import jwtDecode from 'jwt-decode'
...
function saveLBToken({ token } : { token: string }) {
const decoded = jwtDecode(token)
if (decoded && typeof decoded === 'object') {
sessionStorage.setItem(LB4_TOKEN, JSON.stringify({ token, ...decoded }))
} else {
console.log('Bad LB token:', decoded)
}
}
uj5u.com熱心網友回復:
感謝 MaxAlex 的回答,我最終在我的代碼中使用了這個:
export const authProvider = {
// authentication
login: ({ username, password }) => {
const request = new Request(
process.env.REACT_APP_API_URL '/users/login',
{
method: 'POST',
body: JSON.stringify({ email: username, password }),
headers: new Headers({ 'Content-Type': 'application/json' }),
},
);
return fetch(request)
.then((response) => {
if (response.status < 200 || response.status >= 300) {
throw new Error(response.statusText);
}
return response.json();
})
.then((auth) => {
const { id, name, email, exp, iat } = jwtDecode(auth.token);
if (!id || !name || !email || !exp || !iat) {
throw new Error('Invalid token');
}
if (exp < iat) {
throw new Error('Token expired');
}
localStorage.setItem(
'auth',
JSON.stringify({
...auth,
id,
fullName: name,
email,
exp,
iat,
}),
);
})
.catch(() => {
throw new Error('Network error');
});
},
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/520724.html
標籤:反应验证反应管理员环回
