认证通过时userID未定义

userID is undefined when passing authentication

我可以登录并获得令牌和用户名,但用户 ID 未定义。我可以控制台记录所有用户数据用户名和令牌,但 userId 未定义。我在后端使用 entity framework 并创建没有 id 的用户,但我什至尝试使用 id 但它也不起作用。

可能是什么原因?

login(username: string, password: string): Observable<boolean> {
    return this.http.post<any>(environment.apiUrl + '/token', {username, password})
      .pipe(map(response => {
        const token = response.token;
        const userID = response.userID;
        console.log(userID);
        // login successful if there's a jwt token in the response
        if (token) {
          // store username and jwt token in local storage to keep user logged in between page refreshes
          localStorage.setItem('currentUser', JSON.stringify({userID, username, token}));
          // return true to indicate successful login
          return true;
        } else {
          // return false to indicate failed login
          return false;
        }
      }));
  }

后端:

User admin = ctx.Users.Add(new User()
            {
                UserId = 1, (try without it and with)
                Username = "admin",
                PasswordHash = passwordHashAdmin,
                PasswordSalt = passwordSaltAdmin,
                IsAdmin = true,

            }).Entity;

Javascript区分大小写。

在您的 C# 模型中您有:

UserId = 1, (try without it and with)

我认为您使用的是驼峰命名法,因此将从 API 作为 userId 返回。

在 Javascript 你有:

response.userID;

注意 D 是大写字母。将其更改为小写。

此外,如果您这样做的话,您本可以更早地发现这一点:

console.log(response);

检查整个返回的负载。