javascript - 类型 '_id' 上不存在属性 'string | JwtPayload' 。类型 '_id' 上不存在属性 'string'

标签 javascript node.js mongodb jwt

正如您在 NodeJS 代码中看到的那样,我正在从 URL 中提供的 Postman token 中获取用户,但我正在努力从给定的 token 号中取回 _id 属性。我想要的是decoded._id中的那个id,这样我就可以在进一步的操作中使用那个id

const jwt = require('jsonwebtoken')
const User = require('../model/users')
const auth = async (req, res, next) => {
    try {
          const token = req.header('Authorization').replace('Bearer', '')
          const decoded = jwt.verify(token, 'thisisfromabhishek')

`the property _id does not exist on decoded`
          const user = await User.findOne({ _id: decoded._id, 'tokens.token': token })

        if (!user) {
            throw new Error()
        }
        req.token = token
        req.user = user
        next()
       } catch (e) {
        res.status(401).send({ error: 'Please authenticate.' })
    }
}

module.exports = auth

最佳答案

Typescript 不知道 token 中的 _id。
数据声明应该有所帮助。

interface JwtPayload {
  _id: string
}

const { _id } = jwt.verify(token, 'thisisfromabhishek') as JwtPayload

req.user = await User.findOne({ _id, 'tokens.token': token })

关于javascript - 类型 '_id' 上不存在属性 'string | JwtPayload' 。类型 '_id' 上不存在属性 'string',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69479595/

相关文章:

node.js - socket io鼠标点击事件

javascript - 使用 JavaScript/Node.js 实现插件架构

c# - 使用 mongo C# 驱动程序在嵌入式文档中维护 Id 属性名称

ruby-on-rails - Mongoid多对多问题

javascript - 什么是 NODE_ENV 以及如何在 Express 中使用它?

javascript - Google Place 自动完成邮政编码

javascript - 前端应用程序的 Angular 路由

JavaScript 范围 : passing a variable from an outer function to an inner function

javascript - 导入带有属性的 ES6 模块

node.js - 使用 mongoose 和 Fixie(Heroku 附加组件)连接到 mongodb