2017-02-13 6 views
0

braintreeで支払いを処理するために別のサーバーを実行して、アプリに支払いシステムを実装しようとしています。私が理解できないことは、結果のクライアント側を処理するためにクライアントにエラーを送信する方法(支払いが間違っている場合)です。どのようにして、クライアントが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); 
     } 
    }); 
}); 
(この場合はエラー)の応答を送信することができます。 0

お客様のクライアント

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()の代わりにクライアントのフェッチ関数に2番目のパラメータを渡そうとしましたか? 'フェッチ( 'https://test.herokuapp.com/checkout'、{ 方法: "POST"、 ヘッダー:{ 'のContent-Type': 'アプリケーション/ JSON' }、 体:JSON (エラー)=> { console.log(結果)=> { console.log(結果); } (エラー); }); ' – giankotarola

関連する問題