DEV Community

Christy
Christy

Posted on

Need help integrating stripe in react; getting 404

I'm learning how to integrate Stripe into React & Express. I'm getting a 404 error. Also, when I try to console.log the req.body, nothing appears.

on payment button click Expecting "Purchase Complete", getting "Purchase Error" (below)

async submit(ev) {
ev.preventDefault();
let { token } = await this.props.stripe.createToken();
let response = await fetch("http://127.0.0.1:3000/api/charge", {
    method: "POST",
    headers: { "Content-Type": "text/plain" },
    body: token.id
});

if (response.ok) {
    console.log("Purchase Complete")
    this.setState({ complete: true })
} else {
    console.log("Purchase Error")
    console.log(response)
}
}

router:

  router.post("/charge", async (req, res) => {

      console.log("req.body: ", req.body)

  try {
let { status } = await stripe.charges.create({
  amount: 14,
  currency: "usd",
  description: "Purchase 1,000 followers",
  source: req.body
});
res.json({ status });
 } catch (err) {
   res.status(500).end();
 }
});

Expecting to see req.body in console (from above code) but getting nothing. I've tried adding forms of bodyParser in server/src/index.js (below).

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

Top comments (3)

Collapse
 
deadlybyte profile image
Carl Saunders

Usually this issue is due to the order of the middleware being configured. The app.use(bodyParser.text()) has to be configured before the routes are declared.

I've created a glitch project to demonstrate how the code could be implemented.

Good luck 🤞 with getting the issue sorted.

Collapse
 
jbull328 profile image
John Bull

I find I struggle with fetch requests, and generally reach for Axios. Something about the syntax doesn't compute for me. Might be worth a try.
medium.com/@thejasonfile/fetch-vs-...

Here is a quick overview of the differences I found.

The examples within do a fetch.then passing the results to another function. Maybe that is it.

Collapse
 
christycakes profile image
Christy • Edited

After going through a whole troubleshoot checklist, including suggestions below (thank you), I went back to the beginning and thought about the error message 404. I looked at my url and the stripe documentation again. Changing

http://127.0.0.1:3000/api/charge

to

/charge

solved it. However, I'm not sure why. My other fetch requests on this app use the longer version. Can anyone explain?