Home:ALL Converter>Send http request in Ionic with Angular http

Send http request in Ionic with Angular http

Ask Time:2017-06-07T02:47:23         Author:maudulus

Json Formatter

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 [email protected]"
  }, function(err, charge) {
    // asynchronously called
  });
  res.send('Hello World!')
});


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

Author:maudulus,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/44397635/send-http-request-in-ionic-with-angular-http
Sachila Ranawaka :

I think you need to map the request before subscribing to the request \n\nthis.http.post(\"http://11.1.1.7:3100/charge\", postParams, options)\n .map(res => res.json())\n .subscribe(data => {\n console.log(data['_body']);\n }, error => {\n console.log(error);// Error getting the data\n });\n\n\nalso, import the rxjs\n\nimport 'rxjs/Rx';\n",
2017-06-06T18:52:08
yy