Jason Maynard
Jason Maynard

Reputation: 359

Error 404 POST form data from react to express

I am trying to post data from a form (react) to my backend (nodejs/express), but I am getting a 404 error. There is a lot of code here, so I've tried to post just what is important.

Function to submit

  //submit data
  const submitCard = (ev) => {
    console.log(ev);
    ev.preventDefault();

    try {
      api.post('/api/stripe/', payment).then((result) => {
        window.location.href = process.env.REACT_APP_REDIRECT_URI;
      });
    } catch (e) {
      console.log(e);
    }
  };

data being submitted

  const paymentUpdated = () => {
    setPayment({
      name: name,
      firstName: firstName,
      lastName: lastName,
      cardNumber: number,
      expDate: expiry,
      cvc: cvc,
      zip: zip,
      plan: plan,
    });
  };

form tag + button

<form className="creditForm" onSubmit={submitCard}>
<Button className="save-button" type="submit">

route being submitted to (still need send data to stripe)

 app.post('/api/stripe', requireLogin, async (req, res) => {
    const plan = await stripe.plans.retrieve('price_1HfAZGGFN31Q4RRjSrFXnGgD');
    console.log(req);
    if (req.user.stripeId) {
      const customer = await stripe.customers.retrieve(req.user.stripeId);
    } else {
      const customer = await stripe.customers.create({
        email: req.user.email,
        description: 'Subscribing to Personal Plan Monthly Subscription',
      });
      req.user.stripeId = customer.id;
      const user = await req.user.save();
    }
    req.user.plan = 2;
    const user = await req.user.save();
    const subscription = await stripe.subscriptions.create({
      customer: req.user.stripeId,
      items: [{ price: 'price_1HfAZGGFN31Q4RRjSrFXnGgD' }],
    });

Upvotes: 0

Views: 662

Answers (1)

Mark Small
Mark Small

Reputation: 414

It looks like there is an inconsistency in the URL your posting to and that configured in express. Your posting to /api/stripe/, but express is setup to listen for /api/stripe, note the lack of trailing / in express. So it is not finding the endpoint you are expecting.

I tend to test my APIs using curl commands e.g.

curl -X POST "http://localhost:3500/api/stripe/" -H  "content-type: application/json" -d '{"key1": "value1", "key2": "value 2"}'

Once I have proven the API works, only then do I worry about calling it from an app. This will make it easier to identify where the problem lies, in your code.

Upvotes: 2

Related Questions