向客户端发送错误作为HTTP请求的回调 [英] Sending an error to client as callback of HTTP request
问题描述
我正在尝试通过运行单独的服务器以使用Braintree处理付款来在我的应用中实施付款系统.我不知道如何将错误发送给客户(付款出错时),以处理客户端的结果.我怎么能强迫我的客户去追赶而不是根据result.success呢?或者如何在.then中获得result.success?实际上我的结果对象没有包含我的result.success的属性 (result.success是布尔值)
I’m trying to implement a payment system in my app by running a separate server to handle payments with braintree. What I can’t figure out is how do I send an error to my client (when the payment went wrong) to handle the result client side. How can I force my client to go in the catch instead of then based on result.success ? Or how do I get the result.success in my .then ? Actually my result object has no property containing my result.success (result.success is a boolean)
服务器:
router.post("/checkout", function (req, res) {
var nonceFromTheClient = req.body.payment_method_nonce;
var amount = req.body.amount;
gateway.transaction.sale({
amount: amount,
paymentMethodNonce: nonceFromTheClient,
}, function (err, result) {
res.send(result.success);
console.log("purchase result: " + result.success);
});
});
客户:
fetch('https://test.herokuapp.com/checkout', {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ payment_method_nonce: nonce, amount: this.props.amount })
}).then((result) => {
console.log(result);
}).catch(() => {
alert("error");
});
}
推荐答案
假设您使用的是express,您可以使用以下状态代码(在这种情况下为错误)发送响应:
Assuming that you are using express, you can send the response with a status code(in this case an error) like this:
router.post("/checkout", function (req, res) {
var nonceFromTheClient = req.body.payment_method_nonce;
var amount = req.body.amount;
gateway.transaction.sale({
amount: amount,
paymentMethodNonce: nonceFromTheClient,
}, function (err, result) {
if(err){
res.status(401).send(err); //could be, 400, 401, 403, 404 etc. Depending of the error
}else{
res.status(200).send(result.success);
}
});
});
在您的客户中
fetch('https://test.herokuapp.com/checkout', {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ payment_method_nonce: nonce, amount: this.props.amount })
}).then((result) => {
console.log(result);
}).catch((error) => {
console.log(error);
});
这篇关于向客户端发送错误作为HTTP请求的回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!