问题
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)
Server:
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);
});
});
Client :
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");
});
}
回答1:
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);
}
});
});
And in your client
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);
});
来源:https://stackoverflow.com/questions/42209347/sending-an-error-to-client-as-callback-of-http-request