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

标签 angularjs node.js ionic-framework localhost stripe-payments

我有一个 ionic 应用程序,我正在尝试将我的 Stripe token 发送到该应用程序,以进行付款处理。当我使用 curl 将请求发送到 node 服务器时,它正在接收请求。然而,当我尝试通过 Angular 的 http 模块发送请求时,它根本没有注册。所有这些目前都在本地进行测试,因此这可能是问题的一部分?

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 服务器

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!')
})

最佳答案

我认为您需要在订阅请求之前映射请求

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
      });

另外,导入rxjs

import 'rxjs/Rx';

关于angularjs - 使用 Angular http 在 Ionic 中发送 http 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44397635/

相关文章:

javascript - AngularJs 和 Codeigniter 路由导致无限重定向循环

javascript - 移动浏览器上的 AngularJS 和 ASP.Net WebAPI 社交登录

Javascript 将数组转换为对象

android - Cordova BluetoothLE 仅检测 mac 笔记本电脑而不检测其他设备?

html - Ionic App 中模态的 ionic 滑动框问题

javascript - AngularJS:指令在页面上多次并发出/广播处理

javascript - 服务变量更改时范围值不更新

node.js - 使用 nodejs 发送 formData POST 请求

javascript - 使用 CoffeeScript 支持设置 Node.js/Geddy 应用程序

javascript - Ionic App 的 javascript 错误 : No 'Access-Control-Allow-Origin' header is present on the requested resource