Skip to content Skip to sidebar Skip to footer

Sending An Error To Client As Callback Of Http Request

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 clien

Solution 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);
});

Post a Comment for "Sending An Error To Client As Callback Of Http Request"