ios - 创建 Stripe 客户 ID 时出现 Alamofire 错误 (iOS)

标签 ios node.js swift alamofire stripe-payments

我在使用 Node.js(集成 Stripe)的 Heroku 应用程序中使用 Alamofire 和 Swift。但是,在创建客户 ID 时,出现以下错误。我的代码集如下。

如果需要了解任何其他详细信息,请告诉我。

Error message: Alamofire.AFError.responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)

客户端代码

func createCustomerKey(withAPIVersion apiVersion: String, completion: @escaping STPJSONResponseCompletionBlock) {

    let customerIDURL = self.baseURL.appendingPathComponent("customer")
    let customerIDParameters = ["email":(Auth.auth().currentUser?.email)!]

    Alamofire.request(customerIDURL, method: .post, parameters: customerIDParameters, encoding: JSONEncoding.default).validate(statusCode: 200..<300).responseJSON { responseJSON in

        switch responseJSON.result {
            case .success(let json):
                completion(json as? [String:AnyObject], nil)
                print("\(json)\n\n\n\n")
            case .failure(let error):
                completion(nil, error)
                print("Error message:\(responseJSON.result.error)")
                break
        }
    }

服务器端代码

const express = require('express')
const path = require('path')
const PORT = process.env.PORT || 5000

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

app.set('port', (process.env.PORT || 5000));

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({
  extended: true
}));

app.use(express.static(path.join(__dirname, 'public')));

app.set('views', path.join(__dirname, 'views'));

app.set('view engine', 'ejs');

app.listen(PORT, () => console.log(`Listening on ${ PORT }`));

app.post('/customer', (req, res) => {

  var email = req.body.email;

  stripe.customers.create({
    email: email
  }, function(err) {
    if (err) {
      console.log(err, req.body)
      res.status(500).end()
    } else {
      res.status(200).send()
    }
  }

最佳答案

该错误消息意味着 Alamofire 在处理响应 JSON 时失败。

具体来说,问题似乎出在服务器端 - 据我所知,您没有从服务器发回有效的 JSON 响应,只是状态代码 200。

要发回数据,您需要向 res.send() 提供一个参数,例如:

res.status(200).send({'email':email})

此外,Stripe API docs声明回调函数接收两个参数,第二个参数是客户对象。所以代码可以这样实现:

stripe.customers.create({
  email: email
}, function(err, customer) {
  if (err) {
    res.status(500).end()
  } else {
    res.status(200).send(customer)
  }
}

关于ios - 创建 Stripe 客户 ID 时出现 Alamofire 错误 (iOS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51046268/

相关文章:

ios - 是否可以不重用 UITableView 中的特定单元格?

node.js - Knex 实例无法连接到 PostgreSQL DB : Unhandled rejection Error: role "19016" doesn't exist

node.js - Nodejs 在提供单线程环境的同时如何处理多个客户端

javascript - 将对象推送到 JSON 文件子数组/对象

ios - iOS13 上 UIControlSegment 背景色不再透明

ios - Pod :Module 的未定义局部变量或方法

android - FireMonkey 访问 Android 或 iOS 上的 SQL Server

ios - 对来自 FBSDKGraphRequest 的结果进行类型化访问(FBSDK v 4.1.0)

ios - UIImageView 在下一个 ViewController 打开时与 UILabel 重叠

ios - 无法在 iPhone X Swift 中获取当前位置