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

标签 javascript node.js paypal httprequest braintree

我正在尝试通过运行单独的服务器来在我的应用程序中实现支付系统,以使用 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/

相关文章:

javascript - 如何让 HTML 按钮依次运行三个功能

javascript - 在 Chrome 中检测被阻止的弹出窗口

javascript - 使用 Backbone 和 Marionette 基于子路由更改布局区域

javascript - 如何为 PayPal Express Checkout 配置 IPN?

php - 第三方支付处理并在支付完成后授予用户访问权限

javascript - 表单元素不打印?

javascript - 使用 Bluebird.js 和 Twitter 流的 promise 和流

mysql - 如何使用nodejs将excel文件导入到mysql

node.js - 尝试安装nodemon时出现错误

paypal - 将借记卡添加到 paypal 吗?