在Ionic 4中,尝试将令牌发送到Express路由,但无法验证令牌甚至在存储中

时间:2019-10-30 13:43:40

标签: angular ionic4

我正在尝试将标头中的令牌发送到我的Express路由,遇到了麻烦,因此我想验证令牌是否已在存储中设置。无法检查。

authentication.service.ts

  login(user: User): Observable<AuthResponse> {
    return this.httpClient.post(`${this.AUTH_SERVER_ADDRESS}/login`, user).pipe(
      tap(async (res: AuthResponse) => {
        if (res.user) {
          console.log("res.user:" + res.user.access_token);
          await this.storage.set("ACCESS_TOKEN", res.user.access_token);
          await this.storage.set("EXPIRES_IN", res.user.expires_in);
          this.authenticationState.next(true);
        }
      })
    )
  }

console.log每行显示undefined。如何验证是否在存储中设置了这些值?

该帖子的回复是: enter image description here

快速路线:

router.post('/login', (req, res) => {
    const email = req.body.email;
    const form_password = req.body.password;
    findUserByEmail(email, (err, user) => {
        if (err) return res.status(500).send({ "message": 'Server error!', "status": '500' });
        if (!user[0]) return res.status(404).send({ "message": 'User not found!', "status": '404' });
        const result = bcrypt.compareSync(form_password, user[0].password);
        if (!result) return res.status(401).send({ "message": 'Password not valid!', "status": '401' });
        const expiresIn = 24 * 60 * 60;
        user[0].access_token = jwt.sign({ id: user[0].id }, process.env.SECRET_KEY, {
            expiresIn: expiresIn
        });
        res.status(200).send({ "user": user, "expires_in": expiresIn, "message": 'Success!', "status": '200' });
    });
});
console.log("res.user:" + JSON.stringify(res.user));

导致:

res.user:[{"id":1,"name":"Admin","email":"Admin@test.com","password":"$2a$10$2OaS5CyGKMSF5J8wed5W7.qyNFYrPScBM49SgU7L9MBMVF0RWxx1e","created_at":"2019-10-16T13:28:06.000Z","access_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNTcyNDU1MTk3LCJleHAiOjE1NzI1NDE1OTd9.2eFbQ294TG6gvKUxSyaQGDBEas7ZLFT8k9H7jnpOoXQ"}]```

1 个答案:

答案 0 :(得分:0)

我弄清楚了,因为我正在发送user []数组,所以我不得不将res.user检查为数组。

          await this.storage.set("ACCESS_TOKEN", res.user[0].access_token);
          await this.storage.set("EXPIRES_IN", res.user[0].expires_in);

一旦我这样做,它就会起作用!