0

I'm trying to setup a subscription service using React on the Frontend, and Node on the Backend. As of now, I've only had success passing the token.id that is generated from this.props.stripe.createToken. The problem I'm having is sending additional info about the customer to my server. How can I pass additional data from the frontend to the server?

I understand that

body: JSON.stringify({ token: token.id, email: 'xxx' })

helps me submit more data, but how do I extract that info on the server-side? If I console.log(req.body), an empty object is returned

Solved I only had BodyParser processing text, when I really wanted it to be processing JSON. Adding app.use(bodyParser.json()); fixed it. No more empty req.body!!!

Frontend

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

Backend

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'));
WMG
  • 9
  • 3
  • Where you're passing `body: token.id`, change it to `body: JSON.stringify({token: token.id, email: xxx})`. Possible duplicate of [Fetch: POST json data](https://stackoverflow.com/questions/29775797/fetch-post-json-data) – laggingreflex Aug 18 '19 at 17:52
  • @laggingreflex but how do I extract that info on the server-side? If I console.log req.body, it's showing an empty object {} – WMG Aug 18 '19 at 17:57
  • Are you using bodyparser? See https://stackoverflow.com/questions/52684372/fetch-post-request-to-express-js-generates-empty-body – laggingreflex Aug 18 '19 at 18:08
  • @laggingreflex that solved it! Thank you!!! – WMG Aug 18 '19 at 18:23

1 Answers1

1

You can simply pass an abject to JSON.stringify (JSON) to the body attribute of your fetch request.

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

You have to update the header Content-Type to pass application/json.

Spleen
  • 2,656
  • 1
  • 10
  • 16
  • Thank you, but how do I extract that info on the server-side? If I console.log req.body, it's showing an empty object {} – WMG Aug 18 '19 at 18:01
  • You should use `JSON.parse(req.body)`, that would give an object of data you have posted. @WMG – Spleen Aug 18 '19 at 18:04
  • Please read my answer again, You need to update the header to the `headers: {'Content-Type': 'application/json'}` @WMG – Spleen Aug 18 '19 at 18:10
  • I've adjusted my code above, but when I try to assign the result to a var, I'm getting an error. Let me know what you think – WMG Aug 18 '19 at 18:19