gpt4 book ai didi

javascript - 如何正确寻址响应数据?

转载 作者:行者123 更新时间:2023-12-02 22:33:45 26 4
gpt4 key购买 nike

在我的身份验证服务中,我需要存储经过身份验证的用户的 ID。我还需要存储访问 token 和用户名。当我转到开发工具的应用程序选项卡时,两者( token 和用户名)都正确存储在存储中(键和值)。但我的 user_id 要么是使用此代码时未定义的值 this.storage.set(USER_ID, res['user_id']); ,要么是当我得到一个值 NaN 时我首先尝试将其转换为数字(这可能是必要的,因为 user_id 是一个数字)。这将是这个版本 this.storage.set(USER_ID, this.validateId(res['user_id']));对于 console.log('my user: ', this.user); 我得到以下数据: my user: {token_type: "access", exp: 123 , user_id: 13}

我做错了什么?由于 user_id 是一个数字,因此它应该有效!

const TOKEN_KEY = 'access_token'; // this is stored
export const USERNAME_KEY = 'username_key'; // this is stored
export const USER_ID = 'user_id'; // this isn't stored
...
user = null;
authenticationState = new BehaviorSubject(false);

constructor(private http: HttpClient, private alertCtrl: AlertController, private storage: Storage, private helper: JwtHelperService,
private plt: Platform) {
this.plt.ready().then(() => {
this.checkToken();
});
}

checkToken() {
this.storage.get(TOKEN_KEY).then(access => {
if (access) {
this.user = this.helper.decodeToken(access);
this.authenticationState.next(true);
}
});
}

validateId(user_id: any): number {
return parseInt(user_id);
}

apilogin(username: string, password: string) {
return this.http.post<any>(`http://127.0.0.1:8000/api/token/`, { username, password })
.pipe(
tap(res => {
this.storage.set(TOKEN_KEY, res['access']); // this is stored
this.storage.set(USERNAME_KEY, username); // this is stored
this.storage.set(USER_ID, this.validateId(res['user_id'])); // this isn't stored
this.user = this.helper.decodeToken(res['access']);
console.log('my user: ', this.user);
this.authenticationState.next(true);
}),
catchError(e => {
this.showAlert('Oops smth went wrong!');
throw new Error(e);
}));
}

最佳答案

如果

this.user = this.helper.decodeToken(res['access']);

在 this.user 中设置此数据

{token_type: "access", exp: 123 , user_id: 13}

您可以使用来自 this.user 的 user_id 属性,而不是来自 res

this.user = this.helper.decodeToken(res['access']);
this.storage.set(USER_ID, this.user['user_id']);

关于javascript - 如何正确寻址响应数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58807792/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com