简体   繁体   English

使用 Angular http 在 Ionic 中发送 http 请求

[英]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.我有一个 ionic 应用程序,我试图将我的Stripe令牌发送到该应用程序以进行付款处理。 When I send the request to the node server with curl it is receiving the request.当我使用curl将请求发送到node服务器时,它正在接收请求。 However, when I try to send the request via Angular's http module, it isn't registering at all.但是,当我尝试通过 Angular 的 http 模块发送请求时,它根本没有注册。 All of this is currently being tested locally, so that might be part of the issue?所有这些目前都在本地进行测试,所以这可能是问题的一部分?

HTML HTML

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

cart.ts购物车.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!')
})

I think you need to map the request before subscribing to the request我认为您需要在订阅请求之前映射请求

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

also, import the rxjs另外,导入rxjs

import 'rxjs/Rx';

I would try this in the stripe.charges.create callback and see what happens:我会在stripe.charges.create回调中尝试这个,看看会发生什么:

}, function(err, charge) {
  if (err) throw err;

  console.log('Charge ID:', charge.id); 

  res.send('Hello World!');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM