当我尝试使用get方法注销时,我想删除令牌。
这是我的get方法:
const { User } = require('./models/user');
const { Book } = require('./models/book');
const { auth } = require('./middleware/auth');
app.get('/api/logout',auth,(req,res)=>{
req.user.deleteToken(req.token,(err,user)=>{
if(err) return res.status(400).send(err);
res.sendStatus(200)
})
})
它使用名为auth的中间件:
const {User} = require('./../models/user');
let auth = (req,res,next) =>{
let token = req.cookies.auth;
User.findByToken(token,(err,user)=>{
if(err) throw err;
if(!user) return res.json({
error:true
});
req.token = token;
req.user = user
return next();
})
}
我的deleteToken函数是:
userSchema.methods.deleteToken = function(token,cb){
var user = this;
user.update({$unset:{token:1}},(err,user)=>{
if(err) return cb(err);
cb(null,user)
})
}
const User = mongoose.model('User',userSchema);
module.exports = { User }
当我与邮递员发送此请求时,它给我错误:
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>TypeError: req.user.deleteToken is not a function
<br> at app.get (/Users/ademozsayin/Desktop/book/server/server.js:39:14)
<br> at Layer.handle [as handle_request] (/Users/ademozsayin/Desktop/book/node_modules/express/lib/router/layer.js:95:5)
<br> at next (/Users/ademozsayin/Desktop/book/node_modules/express/lib/router/route.js:137:13)
<br> at User.findByToken (/Users/ademozsayin/Desktop/book/server/middleware/auth.js:15:16)
<br> at /Users/ademozsayin/Desktop/book/server/models/user.js:80:13
<br> at /Users/ademozsayin/Desktop/book/node_modules/mongoose/lib/model.js:4698:16
<br> at /Users/ademozsayin/Desktop/book/node_modules/mongoose/lib/query.js:4099:12
<br> at process.nextTick (/Users/ademozsayin/Desktop/book/node_modules/mongoose/lib/query.js:2681:28)
<br> at processTicksAndRejections (internal/process/next_tick.js:74:9)
</pre>
</body>
我已经导出了module.exports = { User }
,其他功能都可以使用,但deleteToken()无效。