2017-02-13 4 views
0

braintree로 지불을 처리하기 위해 별도의 서버를 실행하여 앱에 지불 시스템을 구현하려고합니다. 내가 알 수없는 것은 결과 클라이언트 측을 처리하기 위해 고객에게 오류가 발생했을 때 (지불이 잘못되었을 때) 어떻게해야하는지입니다. result.success를 기반으로하지 않고 클라이언트가 catch에 들어가게하려면 어떻게해야합니까? 또는 결과를 얻는 방법. 내. 결과 .uccess? 사실 내 결과 객체 (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

답변 해 주셔서 감사합니다! . 상태 코드가 400 인 경우에도 여전히 .then() 상태가됩니다. 결과에서 내 클라이언트의 상태 코드를 얻을 수 있으므로 거기에 내 논리를 적용 할 수 있습니다. –

+0

당신은 환영합니다! .catch() 대신 클라이언트의 반입 함수에 두 번째 매개 변수를 전달하려고 했습니까? '가져 오기 ('https://test.herokuapp.com/checkout', { 방법 : "POST", 헤더 : { '콘텐츠 유형': '응용 프로그램/JSON' }, 몸 : JSON (결과) => { console.log (결과); }, (오류) => { console.log (오류 코드)} .stringify ({결제 _ 방법론 없음 : 논스, 금액 : this.props.amount} (오류); });' – giankotarola