401:未经授权(包含承载令牌)

时间:2019-11-11 05:01:20

标签: authorization postman access-token

  • 登录模块正在运行,并且正在使用创建的令牌201创建用户
  • 收货路线以前曾使用相同的代码,但现在的响应是401
  • 已使用邮递员(授权和载体:xcvbnm)放置
  • 这是我的代码

    server.js

    const express = require('express') require('./ db / mongoose') const userRouter = require('./ routes / user') const receiveRouter = require('./ routes / receipt')

    const app = express() const port = process.env.PORT || 4003 app.use(express.json()) app.use(userRouter) app.use(接收路由器) app.listen(port,()=> {     console.log('服务器在端口上启动'+端口)    })

    const Receipt = require('./ models / receipt') const User = require('./ models / user')

收据路线

router.post('/receipts', auth, async (req, res) => {
    const receipt = new Receipt({
        ...req.body,
        owner: req.user._id
    })
  try {
        await receipt.save()
        res.status(201).send(receipt)
    } catch (e) {
        res.status(400).send(e)
    }
})

接收模式     const Receipt = mongoose.model('Receipt',{     说明:{         类型:字符串,         要求:正确,         修剪:真     },     })

Auth module
const auth = async (req, res, next) => {
    try {
        const token = req.header('Authorization').replace('Bearer', '')
        const decoded = jwt.verify(token, 'Mango@123')
        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.' })
    }
}

0 个答案:

没有答案