Tuesday 6 June 2017

Send http request in Ionic with Angular http

I have an ionic app that I am trying to send my Stripe token to, for payment processing. When I send the request to the node server with curl it is receiving the request. However, when I try to send the request via Angular's http module, it isn't registering at all. All of this is currently being tested locally, so that might be part of the issue?

HTML

<button (click)="testPost()" ion-button full>TEST POST</button>

cart.ts

...
import {Http, Headers, RequestOptions} from '@angular/http';
import { Stripe } from '@ionic-native/stripe';

@Component({
 selector: 'page-cart',
 templateUrl: 'cart.html',
})
export class Cart {

  constructor(
    ...
    private http: Http,
    private stripe: Stripe
    ) {
      //
    });    
  }

  testPost() {
    var headers = new Headers();
    headers.append("Accept", 'application/json');
    headers.append('Content-Type', 'application/json' );
    let options = new RequestOptions({ headers: headers });

    let postParams = {
      body: {
        token: 'axqrexample123tokenbasdflkjo3',
        amount: 225
      }
    }

    this.http.post("http://11.1.1.7:3100/charge", postParams, options)
      .subscribe(data => {
        console.log(data['_body']);
       }, error => {
        console.log(error);// Error getting the data
      });  
  }

}

NODE SERVER

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var stripe = require("stripe")("sk_test_abcTAdefgn1oDexamplex");

app.use(bodyParser.json());

app.post('/charge', function (req, res) {

  var token = req.body.token;
  var amount = req.body.amount;
  stripe.charges.create({
    amount: amount,
    currency: "usd",
    source: token, // obtained with Stripe.js 
    description: "Charge for jones@example.com"
  }, function(err, charge) {
    // asynchronously called
  });
  res.send('Hello World!')
});


app.listen(3100, function () {
  console.log('Example app listening on port 3100!')
})



via maudulus

No comments:

Post a Comment