【问题标题】:Sending an error to client as callback of HTTP request向客户端发送错误作为 HTTP 请求的回调
【发布时间】:2017-07-01 18:01:18
【问题描述】:

我正在尝试在我的应用中实现支付系统,方法是运行一个单独的服务器来处理 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");
  });
}

【问题讨论】:

    标签: javascript node.js paypal httprequest braintree


    【解决方案1】:

    假设您使用的是 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);
    });
    

    【讨论】:

    • 感谢您的回答!即使状态码为 400,它仍在 .then() 中。但我可以从客户端获取状态码作为结果,所以我在那里制定了我的逻辑 :)
    • 欢迎您!您是否尝试将第二个参数传递给客户端中的 fetch 函数,而不是 .catch()? 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); }, (error) => { console.log(error); });
    猜你喜欢
    • 2021-10-16
    • 1970-01-01
    • 2020-07-15
    • 2015-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-18
    相关资源
    最近更新 更多