我正在使用Express / Node并编写了一些身份验证中间件来检查每个请求的JWT。
我想为路由禁用此中间件(POST' / api / user /')但是我想保留路由的中间件(GET' / api / user / &#39)
。我怎样才能做到这一点?
请参阅以下代码。
app.js
// app.js
app.use('/api/userauth', require('./Controllers/api/userauth.js'))
app.use(require('./Middleware/Authenticate.js'));
app.use('/api/user', require('./Controllers/Api/User.js'));
app.use('/api/item', require('./Controllers/Api/Item.js'));
authenticate.js
//authenticate.js middleware
var token = req.body.token || req.query.token || req.headers['x-access-token'];
if (token) {
jwt.verify(token, secretKey.secretKey, function(err, decoded){
if (err) {
return res.json({
success : false,
message : "failed to auth token."
})
} else {
console.log(decoded);
req.decoded = decoded;
next();
}
})
} else {
res.status(403).send({
success:false,
message:'no token provided'
})
}
}
API / user.js的
router.route('/')
.get(function(req,res){
models.User.findAll({
}).then(function(users){
res.json(users);
})
})
.post(function(req,res){
models.User.create({
username : req.body.username,
password : req.body.password,
firstname : req.body.firstname,
lastname : req.body.lastname
}).then(function(user){
res.json({
"Message" : "Succesfully created user: ",
"User: " : user
});
});
});
module.exports = router;
答案 0 :(得分:0)
老问题但是你去了!
而不是使用空白</ p>
app.use(require('./Middleware/Authenticate.js'));
对于所有路由,只需在子路由器中执行此操作
<强> API / user.js的强>
var authMiddleware = require('./Middleware/Authenticate.js')
router.route('/')
.get(function(req,res){
models.User.findAll({
}).then(function(users){
res.json(users);
})
})
.post(authMiddleware, function(req,res){
models.User.create({
username : req.body.username,
password : req.body.password,
firstname : req.body.firstname,
lastname : req.body.lastname
}).then(function(user){
res.json({
"Message" : "Succesfully created user: ",
"User: " : user
});
});
});
module.exports = router;
现在只有拥有Authenticate Middleware的路线才能获得!