Thursday, 18 May 2017

Angular 2/4 http.post not working

I'm sending a post request via Angular http but the request never reaches the backend. I wrote a few console.logs to trace the data being passed and it works until reaching http.post. The issues is, there are no error messages, so I cannot identify what is not working.

Here is my frontend code

//Checkout method being called in the form
openCheckout() {
    let total = (this.donation * 100);
    let handler = (<any>window).StripeCheckout.configure({
      key: this.stripeTestKey,
      locale: 'auto',
      token: (token: any) => {
        const transaction = new Charge(total, token.id);
        console.log('From navbar nonObject ' + token.id + ' ' + total);
        console.log(transaction + ' From navbar');
        return this.keyService.charge(transaction);
      }
    });
    handler.open({
      name: 'Event',
      description: 'Donation',
      amount: total
    });
    this.donation = 0;
  }

this is keyService.

  charge(transaction: Charge) {
    console.log('From keyservice ' + transaction.amount + ' ' + transaction.token);
    console.log('From keyservice w/ stringify ' + JSON.stringify(transaction));
    const body = JSON.stringify(transaction);
    const headers = new Headers({'Content-type': 'application/json'});
      return this.http.post(this.keysUrlDev + '/charge', body, { headers: headers })
          .map((response: Response) => response.json())
          .catch((error: Response) => Observable.throw(error.json()));
  }

and here is my api request in the backend

router.post('/charge', function(req, res, next) {
  var amount = req.body.amount;
  var token = req.body.token;
  console.log('Charge POSTED ' + amount + ' ' + token );
  stripe.charges.create({
    amount: amount,
    currency: 'usd',
    description: 'Delaware March For Jesus Donation',
    source: token
  }, function(err, charge) {
    if (err) {
      console.log(req.body.amount + ' From POST' + req.body.token);
      return res.status(500).json({
        title: 'An error occured',
        error: err
      });
    }
    console.log('Charge should have worked');
    res.status(201).json({
      message: 'Charged successfully',
      obj: charge
    });
  });
});

Everything is logging correctly in the console but when I submit, there is no post request in the logs, and no transaction charged on Stripe. Can anyone help me out with this?



via Jonathan Corrin

No comments:

Post a Comment