向客户端发送错误作为 HTTP 请求的回调

Sending an error to client as callback of HTTP request

我正在尝试通过 运行 一个单独的服务器在我的应用程序中实现一个支付系统来处理 braintree 的支付。我想不通的是如何向我的客户发送错误(当付款出错时)以处理结果客户端。我怎样才能强迫我的客户赶上而不是然后基于 result.success ?或者如何在我的 .then 中获取 result.success ?实际上我的结果对象没有 属性 包含我的 result.success (result.success 是一个布尔值)

服务器:

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