这是我的代码
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.' })
}
}