Javascript 将错误作为HTTP请求的回调发送到客户端

Javascript 将错误作为HTTP请求的回调发送到客户端,javascript,node.js,paypal,httprequest,braintree,Javascript,Node.js,Paypal,Httprequest,Braintree,我试图在我的应用程序中实现一个支付系统,通过运行一个单独的服务器来处理braintree的支付。我不明白的是,如何向我的客户发送错误(当付款出错时)以处理客户端的结果。我怎样才能强迫我的客户去抓,而不是基于结果。成功?或者我是如何得到结果的。我的成功。那么呢?实际上,我的结果对象没有包含我的结果的属性。success (result.success是一个布尔值) 服务器: router.post("/checkout", function (req, res) { var nonceFrom

我试图在我的应用程序中实现一个支付系统,通过运行一个单独的服务器来处理braintree的支付。我不明白的是,如何向我的客户发送错误(当付款出错时)以处理客户端的结果。我怎样才能强迫我的客户去抓,而不是基于结果。成功?或者我是如何得到结果的。我的成功。那么呢?实际上,我的结果对象没有包含我的结果的属性。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);
});

谢谢你的回答!即使状态代码为400,它仍在.then()中运行。但是我可以在结果中从我的客户那里得到状态码,所以我在那里做了我的逻辑:)你是wlecome!是否尝试将第二个参数传递给客户端中的fetch函数,而不是.catch()<代码>提取('https://test.herokuapp.com/checkout“,{method:“POST”,标题:{'Content Type':'application/json'},正文:json.stringify({payment\u method\u nonce:nonce,amount:this.props.amount}),然后((result)=>{console.log(result);},(error)=>{console.log(error);})