我正在试图找出使用NodeJS处理错误的最佳方法。如果用户注册或信用卡被接受时出错,我需要返回(或显示错误而不是重定向)。问题是如果我尝试使用多个res.redirect,我会收到错误“如果已经设置了标题,则无法设置标题”。我该如何解决这个问题。我已经显示了我想在下面重定向的位置。
谢谢!
app.post('/quiz', function(req, res) {
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('Did not charge or create error' + err);
// return res.redirect('/');
//I WANT TO RETURN TO HOME HERE IF THERES AN ERROR
//I WANT TO RETURN TO HOME HERE IF THERES AN ERROR
//I WANT TO RETURN TO HOME HERE IF THERES AN ERROR
//I WANT TO RETURN TO HOME HERE IF THERES AN ERROR
}
console.log('charged')
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)
// return res.redirect('/');
//I WANT TO RETURN TO HOME HERE IF THERES AN ERROR
//I WANT TO RETURN TO HOME HERE IF THERES AN ERROR
//I WANT TO RETURN TO HOME HERE IF THERES AN ERROR
//I WANT TO RETURN TO HOME HERE IF THERES AN ERROR
});
req.logIn(user, function(err) {
if(err) {
console.log(err);
}
console.log('all looks good')
// If everything looks good I want to redirect to the next page
// If everything looks good I want to redirect to the next page
// If everything looks good I want to redirect to the next page
// If everything looks good I want to redirect to the next page
// res.redirect('/jobquiz');
});
});
});