我正在尝试从我的react应用程序中获取数据来调用一个快速端点,并将主体作为JSON对象传递,以便可以在其中包含更多数据。当我直接将主体设置为token.id时,该调用当前有效,但我想包含更多数据。现在,我只是用该数据构建JSON,但似乎无法使服务器正确处理它。我已经注释掉了代码的工作行,因为我看到调用将其传递到Stripe API,所以我知道这是行得通的。使用新代码,我可以最有效地进行令牌创建,但是创建客户调用不会显示在条纹API上。
import React, {Component} from 'react';
import {CardElement, injectStripe} from 'react-stripe-elements';
class CheckoutForm extends Component {
constructor(props) {
super(props);
this.state = {complete: false};
this.submit = this.submit.bind(this);
}
async submit(ev) {
let {token} = await this.props.stripe.createToken({name: "Name"});
let data ={
id: token.id
}
let response = await fetch("/charge", {
method: "POST",
//Works with the commented code
//headers: {"Content-Type": "text/plain"},
//body: token.id,
headers: {"Content-Type": "application/json"},
body: JSON.stringify(data)
}).then(response => response.json());
if (response.ok) console.log("Purchase Complete!")
if (response.ok) this.setState({complete: true});
}
render() {
if (this.state.complete) return <h1>Purchase Complete</h1>;
return (
<div className="checkout">
<p>Would you like to complete the purchase?</p>
<CardElement />
<button onClick={this.submit}>Send</button>
</div>
);
}
}
export default injectStripe(CheckoutForm);
这是我的服务器代码:
const app = require("express")();
const stripe = require("stripe")("sk_test_oE2EqjsM7mWqgRRwaomptrdX");
app.use(require("body-parser").text());
app.post("/charge", jsonParser, async (req, res) => {
try {
var userdata = JSON.parse(req.body);
let {status} = stripe.customers.create({
description: "Test Person",
//Commented code currently works
//source: req.body
//Below is how I expected this to work when passing the body as JSON
source: userdata.id
});
res.json({status});
} catch (err) {
res.status(500).end();
}
});
app.listen(9000, () => console.log("Listening on port 9000"));