【发布时间】:2019-12-24 02:19:40
【问题描述】:
我正在尝试使用前端的 React 和后端的 Node 来设置订阅服务。到目前为止,我只成功传递了从 this.props.stripe.createToken 生成的 token.id。我遇到的问题是将有关客户的其他信息发送到我的服务器。如何将额外的数据从前端传递到服务器?
我明白了
body: JSON.stringify({ token: token.id, email: 'xxx' })
帮助我提交更多数据,但如何在服务器端提取这些信息?如果我console.log(req.body),返回一个空对象
已解决
当我真的希望它处理 JSON 时,我只有 BodyParser 处理文本。添加app.use(bodyParser.json()); 修复它。不再有空的 req.body !!!
前端
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: 'Bobby' });
console.log(token);
let response = await fetch('/charge', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token: token.id, email: 'xxx' })
});
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_vXWqlxlbpuHTqQgGIUtqOa9c');
const bodyParser = require('body-parser');
app.use(bodyParser.text());
app.use(bodyParser.json());
app.post('/charge', async (req, res) => {
let newVar = JSON.parse(req.body);
console.log('new var', newVar);
try {
// 1. Create Customer
stripe.customers.create(
// where do I pass this info from the frontend?
{
email: 'jenny.rosen@example.com',
source: 'tok_visa'
},
function(err, customer) {}
);
res.json({ status });
} catch (err) {
res.status(500).end();
}
});
app.listen(9000, () => console.log('Listening on port 9000'));
【问题讨论】:
-
你在哪里经过
body: token.id,把它改成body: JSON.stringify({token: token.id, email: xxx})。 Fetch: POST json data 的可能重复项 -
@laggingreflex 但如何在服务器端提取该信息?如果我 console.log req.body,它显示一个空对象 {}
-
你在使用bodyparser吗?见stackoverflow.com/questions/52684372/…
-
@laggingreflex 解决了它!谢谢!!!
标签: javascript node.js reactjs stripe-payments