POST http://localhost:3000/ 404 (Not Found)

Have searched but unfortunately can’t find a solution to my problem. I’m trying to set up a simple checkout using Stripe, but when making the POST request to the server I’m getting a 404 not found error.

This is the React component making the request…

import React from 'react';

import { loadStripe } from "@stripe/stripe-js";

const stripePromise = loadStripe('pk_test_51HsU13KfqoJqYlMIjzYUCqOrTK2ir9667kEP2SuxLc7GeSuuskLd2TTxty4vdflHDCRCnPpUuOYqoygZMGb1OQ4G00jxacetm0');

const StripeCheckoutButton = () => {

    const handleClick = async (event) => {
        const stripe = await stripePromise;
        const response = await fetch("/create-checkout-session", {
          method: "POST",
        });
        const session = await response.json();
        // When the customer clicks on the button, redirect them to Checkout.
        const result = await stripe.redirectToCheckout({
          sessionId: session.id,
        });
        if (result.error) {
          alert('Payment failed. Error: '+ result.error.message);
          console.log(result.error.message)
        }
      };


return (
    <button id="checkout-button" role="link" onClick={handleClick}>
      Checkout
    </button>
    )
}

export default StripeCheckoutButton;

and this is the server…

require('dotenv').config({ path: './.env'});

const express = require('express');
const cors = require('cors');
const path = require('path');

if (process.env.NODE_ENV !== 'production') require('dotenv').config();
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);

const app = express();
const port = process.env.PORT || 4242;
app.use(express.urlencoded({extended: true})); 
app.use(express.json());

app.use(cors());

if (process.env.NODE_ENV === "production") {
    app.use(express.static(path.join(__dirname, 'client/build')));

    app.get('*', function(req, res) {
        res.sendFile(path.join(__dirname, 'client/build', index.html))
    });
}


const YOUR_DOMAIN = 'http://localhost:3000/checkout';

app.post('/create-checkout-session', async (req, res) => {
  const session = await stripe.checkout.sessions.create({
    payment_method_types: ['card'],
    line_items: [
      {
        price_data: {
          currency: 'gbp',
          product_data: {
            name: 'Stubborn Attachments',
            images: ['https://i.imgur.com/EHyR2nP.png'],
          },
          unit_amount: 2000,
        },
        quantity: 1,
      },
    ],
    mode: 'payment',
    success_url: `${YOUR_DOMAIN}?success=true`,
    cancel_url: `${YOUR_DOMAIN}?canceled=true`,
  });
  res.json({ id: session.id });
});

app.listen(port, error => {
    if (error) throw error;
    console.log("server running on port" + port);
});

Have searched but unfortunately can’t find a solution to my problem. I’m trying to set up a simple checkout using Stripe, but when making the POST request to the server I’m getting a 404 not found error.

This is the React component making the request…

import React from 'react';

import { loadStripe } from "@stripe/stripe-js";

const stripePromise = loadStripe('pk_test_51HsU13KfqoJqYlMIjzYUCqOrTK2ir9667kEP2SuxLc7GeSuuskLd2TTxty4vdflHDCRCnPpUuOYqoygZMGb1OQ4G00jxacetm0');

const StripeCheckoutButton = () => {

    const handleClick = async (event) => {
        const stripe = await stripePromise;
        const response = await fetch("/create-checkout-session", {
          method: "POST",
        });
        const session = await response.json();
        // When the customer clicks on the button, redirect them to Checkout.
        const result = await stripe.redirectToCheckout({
          sessionId: session.id,
        });
        if (result.error) {
          alert('Payment failed. Error: '+ result.error.message);
          console.log(result.error.message)
        }
      };


return (
    <button id="checkout-button" role="link" onClick={handleClick}>
      Checkout
    </button>
    )
}

export default StripeCheckoutButton;

and this is the server…

require('dotenv').config({ path: './.env'});

const express = require('express');
const cors = require('cors');
const path = require('path');

if (process.env.NODE_ENV !== 'production') require('dotenv').config();
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);

const app = express();
const port = process.env.PORT || 4242;
app.use(express.urlencoded({extended: true})); 
app.use(express.json());

app.use(cors());

if (process.env.NODE_ENV === "production") {
    app.use(express.static(path.join(__dirname, 'client/build')));

    app.get('*', function(req, res) {
        res.sendFile(path.join(__dirname, 'client/build', index.html))
    });
}


const YOUR_DOMAIN = 'http://localhost:3000/checkout';

app.post('/create-checkout-session', async (req, res) => {
  const session = await stripe.checkout.sessions.create({
    payment_method_types: ['card'],
    line_items: [
      {
        price_data: {
          currency: 'gbp',
          product_data: {
            name: 'Stubborn Attachments',
            images: ['https://i.imgur.com/EHyR2nP.png'],
          },
          unit_amount: 2000,
        },
        quantity: 1,
      },
    ],
    mode: 'payment',
    success_url: `${YOUR_DOMAIN}?success=true`,
    cancel_url: `${YOUR_DOMAIN}?canceled=true`,
  });
  res.json({ id: session.id });
});

app.listen(port, error => {
    if (error) throw error;
    console.log("server running on port" + port);
});

App lives in a client folder, server lives in the root.

Let me know if you need any more information and thank you in advance :slight_smile:

did you check your app on server is running on port 3000

yes it’s running on port 3000. Actually I’ve just realised that I had the wrong port down as the proxy for the server. However I’ve fixed this, and now the request just hangs forever as ‘pending’. Still no wiser as to why

can you access your api route through postman? also in react component while fetching give the complete url there