【问题标题】:How do I pass additional data from the client-side Stripe Checkout to the server with Fetch如何使用 Fetch 将附加数据从客户端 Stripe Checkout 传递到服务器
【发布时间】: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


【解决方案1】:

您可以简单地将 abject 传递给 JSON.stringify (JSON) 到您的 fetch 请求的 body 属性。

...
let response = await fetch('/charge', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({
        token: '',
        name: '',
        userid: 123,
    }),
})
...

您必须更新标头 Content-Type 以传递 application/json

【讨论】:

  • 谢谢,但是如何在服务器端提取该信息?如果我 console.log req.body,它显示一个空对象 {}
  • 您应该使用JSON.parse(req.body),这将提供您发布的数据对象。 @WMG
  • 请再次阅读我的答案,您需要将标题更新为headers: {'Content-Type': 'application/json'}@WMG
  • 我已经调整了上面的代码,但是当我尝试将结果分配给一个 var 时,我得到了一个错误。让我知道你的想法
猜你喜欢
  • 2020-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-05
  • 1970-01-01
  • 2017-05-13
  • 1970-01-01
相关资源
最近更新 更多