错误后重定向?
问题描述:
我有一个设置让我们的用户使用PassportJS创建一个帐户,并使用Stripe同时收费。这一切都有效。错误后重定向?
问题是,这是目前允许用户使用相同的用户名注册。该函数捕获user.save部分中的错误。但是,即使它发现错误,它仍然会完成创建新用户并对其进行收费。我需要回到那里。然而,我一直无法弄清楚如何res.redirect或在那一部分。
如何更改我的代码以便在那里重定向错误?
app.post('/quiz', function(req, res) {
var user = new User({
username: req.body.username,
email: req.body.email,
password: req.body.password,
datapoint: req.body.datapoint
})
user.save(function(err) {
console.log('this is the problem' + ' ' + err)
if(err){
// I NEED TO REDIRECT BACK HERE IF THERE IS AN ERROR
// I NEED TO REDIRECT BACK HERE IF THERE IS AN ERROR
// I NEED TO REDIRECT BACK HERE IF THERE IS AN ERROR
// I NEED TO REDIRECT BACK HERE IF THERE IS AN ERROR
// I NEED TO REDIRECT BACK HERE IF THERE IS AN ERROR
}
var token = req.body.stripeToken; // Using Express
var charge = stripe.charges.create({
amount: 749,
currency: "usd",
description: "Example charge",
source: token,
}, function(err, charge) {
if(err) {
console.log(err);
}
console.log('charged')
req.logIn(user, function(err) {
if(err) {
console.log(err);
}
console.log('all looks good')
res.redirect('/jobquiz');
});
});
});
});
答
使用return
之前res.redirect()
。它会停止执行。
if (err)
return res.redirect('/anywhere');
答
首先,你需要独特的验证您的用户名,这样,如果没有使用相同的用户名企图,唯一的错误将被抛出。正如你使用猫鼬,我建议npm install mongoose-unique-validator
。将您的用户名设置为唯一。 more info.
其次,捕获错误并重定向到当前窗体(前提交的形式)
if (err) {
// clear cache to prevent 304 response
res.header('Cache-Control', 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0');
return res.redirect('back');
}
'back'
是对req.get('Referrer')
而你的情况提交表单价值基础。