我正在尝试通过运行单独的服务器来在我的应用程序中实现支付系统,以使用 braintree 处理支付。我想不通的是如何向我的客户发送错误(当付款出错时)以处理结果客户端。我怎样才能强制我的客户 catch 而不是然后基于 result.success ?或者如何在我的 .then 中获得 result.success ?实际上我的结果对象没有包含我的 result.success 的属性 (result.success 是一个 bool 值)
服务器:
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,您可以像这样发送带有状态代码(在本例中为错误)的响应:
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);
});
关于javascript - 向客户端发送错误作为 HTTP 请求的回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42209347/