2017-02-13 238 views
0

我试图通过运行单独的服务器来处理与braintree的支付在我的应用程序中的支付系统。我无法弄清楚的是,如何向客户端发送错误(当付款出错时)来处理结果客户端。我如何强制我的客户进入catch而不是基于result.success?或者我如何在我的.then中获得result.success?其实我的结果对象有一个包含我的result.success 没有财产(result.success是一个布尔值)作为HTTP请求的回调向客户端发送错误

服务器:

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

回答

1

假设你正在使用快递,您可以使用状态代码(在此情况下为错误)发送响应,如下所示:

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

感谢您的回答!它仍然在.then()中,即使是状态码400.但是我可以从我的客户端得到状态代码,所以我在那里创建了我的逻辑:) –

+0

你真棒!您是否尝试将第二个参数传递给客户端中的获取函数,而不是.catch()? '取( 'https://test.herokuapp.com/checkout',{ 方法: “POST”, 标头:{ '内容 - 类型': '应用/ JSON' }, 体:JSON .stringify({payment_method_nonce:nonce,amount:this.props.amount}) })。then((result)=> {console.log(result); },(error)=> {console.log (error); });' – giankotarola

相关问题