Despite having a valid API route, an error occurred in the POST request using Axios

Currently, I am following a video tutorial (here) and specifically on part 8 which covers payment processing. The payment process involves using Stripe, Axios, and Node.js. However, whenever attempting to make a POST request to one of the API's routes, a CORS error and Internal Server Error are encountered.

The payment page is embedded as a component in React. When proceeding to checkout, errors appear in the console:

"Access to XMLHttpRequest at 'http://127.0.0.1:5001/clone-e99f7/us-central1/api/payments/create?total=2999' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource." Where the total represents the purchase cost multiplied by 100.

&

"POST net::ERR_FAILED 500 (Internal Server Error)"

In the payment component code snippet:

    const [{ basket, user }, dispatch] = useStateValue();
    const navigate = useNavigate();

    const stripe = useStripe();
    const elements = useElements();

    const [succeeded, setSucceeded] = useState(false);
    const [processing, setProcessing] = useState("");
    const [error, setError] = useState(null);
    const [disabled, setDisabled] = useState(true);
    const [clientSecret, setClientSecret] = useState(true);

    useEffect(() => {
        const getClientSecret = async () => {
          try {
            const response = await axios({ // The error is likely here
                method: "post",
                url: `/payments/create?total=${getBasketTotal(basket) * 100}`,
            });
            setClientSecret(response.data.clientSecret);
          } 
          catch (error) {
            console.log(error) // Error is never logged
          }
        };
      
        getClientSecret();
    }, [basket]);

Where the basket contains user-selected items for purchase.

In the index.js file:

const functions = require("firebase-functions");
const express = require("express");
const cors = require("cors");
const stripe = require("stripe")(/* secret key */);

// API

// - App config
const app = express();

// - Middlewares
app.use(cors({ origin: true }));
app.use(express.json());

// - API routes
app.get("/", (request, response) => response.status(200).send("This is working"));

app.post("/payments/create", async (request, response) => {
console.log("Payment Request Received for this Amount: ", total);
const total = request.query.total;

const paymentIntent = await stripe.paymentIntent.create({
amount: total,
currency: "usd",
});

response.status(201).send({
clientSecret: paymentIntent.client_secret,
});
});

// - Listen command
exports.api = functions.https.onRequest(app);

And within the axios.js file:

import axios from "axios"

const instance = axios.create({
baseURL: "http://127.0.0.1:5001/clone-e99f7/us-central1/api" // API (cloud function) URL
})

export default instance;

Despite the API URL functioning correctly, issues arise when making a POST request to /payments/create?total=x resulting in the mentioned errors. The application is run using the firebase emulators:start command.

Tried utilizing cors({origin: "*"}) without success. Any suggestions?

Answer №1

When sending a post request to the server, it's important to specify the data you want to send. Even if the data is empty, you can still include an empty object like this:

const response = await axios({ 
   method: "post",
   url: `/payments/create?total=${getBasketTotal(basket) * 100}`,
   data: {}
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

react-scripts: command missing within the React application

While running my react-app on localhost, an unexpected error occurred. Even though I have installed all the necessary dependencies using npm install, it seems to be unable to locate the react-scripts command for some unknown reason. ...

issue encountered while using npm to install aframe

Having some trouble installing aframe and aframe-inspector for local development. I've tried various methods, but keep encountering errors during npm install or npm start. When attempting to install aframe, I encounter an error during npm install. For ...

What is the best way to transfer the src module into the public folder in a React project

When utilizing Firebase Cloud Messaging in my React application, I need to place the firebase-messaging-sw.js file in the public folder. Within this file, there is a function defined for onBackgroundMessage, which I want to access from my module and use t ...

Tracking tool for monitoring progress of HTTP POST requests

Hi, I am still a beginner when it comes to NodeJS and its modules. I could really use some assistance with creating a progress bar for an application I'm working on. Right now, the progress bar only reaches 100% upon completion and I suspect my piping ...

How to update a nested array within an array in MongoDB using Mongoose and Node.js

Hello there, I'm currently working on updating an embedded document within another embedded document. The structure of my "object" is as follows: { _id:0, fieldOne:"f1", fieldTwo : "f2", subDocument:[ { _id:0, ...

The success function in Ajax is constantly elusive, while the error function prevails. The data just can't seem to make it to the destination file

Thank you for your patience. This marks my initial post to the best of my recollection. The section below showcases a snippet from my calendar.js script. My current objective involves sending data obtained from a modal window in index.php over to sql.php. ...

What is the best way to send POST values to a PHP page?

I have a register.php page where I send data through a form to a php_register.php file. The php_register.php file validates the form (such as checking if the email is real) and I want it to redirect back to the register.php file if the form is invalid: he ...

Issue with `import type` causing parse error in TypeScript monorepo

_________ WORKSPACE CONFIGURATION _________ I manage a pnpm workspace structured as follows: workspace/ ├── apps/ ├───── nextjs-app/ ├──────── package.json ├──────── tsconfig.json ├───── ...

Tips on receiving feedback from an express server regarding an error by utilizing axios within a react application

Currently, I am working with react and express. In my react application, I am trying to utilize axios.post to send user credentials to the express server in hopes of receiving a response. Once I receive the response, my goal is to extract the message and s ...

Checking the behavior of the menu vanishing upon clicking a button in material-ui (App functioning correctly while the test is failing)

I developed a custom menu component inspired by material-ui's example for a simple menu to implement language change functionality in my application. While the menu functions correctly in the browser, I encountered an issue with the final assertion te ...

What is the best way to integrate @uirouter in the Angular/sampleapp project?

Having trouble configuring the angular/sampleapp to work with @uirouter. Is the systemjs.config.js file set up incorrectly to include @uirouter? 1) Run npm i -S @uirouter/angular 2) Add the following line to the map section in systemjs.config.js ' ...

What is the functionality of the cookie-session middleware in Express.js?

Could someone explain the underlying concepts of cookie-session in expressjs to me? When we store something in session, like this: req.session.myName = "Manas Tunga"; Where is this session data actually stored? Is it in client-side session cookies or in ...

Best practices for executing an asynchronous forEachOf function within a waterfall function

I've been working with the async library in express js and I'm encountering an issue when using two of the methods alongside callbacks. The variable result3 prints perfectly at the end of the waterfall within its scope. However, when attempting t ...

Is there a method, like an API, available in Node.js to programmatically execute a local npm publish command without using the spawning process?

I am in the process of retrieving a list of files from a local package that will be published via npm. I have found a potential solution by utilizing npm publish --dry-run using child_processes.spawn(...) or a similar method. However, this approach is no ...

Unlocking the Power of NextJS Keyframes

After successfully creating a background with 3 images using keyframes in my initial project built with html and css, I decided to recreate the project using NextJS. However, I encountered an issue where the third image does not display in NextJS. Instead ...

An error in npm occurred: "The name "@types/handlebars" is invalid."

While attempting to install typedoc using npm, I encountered the following error: npm ERR! Invalid name: "@types/handlebars" To resolve this issue, I proceeded to install @types/handlebars directly by running: npm install @types/handlebars However, I r ...

Tips for transferring a calculated value from a child component to a parent component in ReactJs

In my current project, I am faced with the challenge of passing a calculated value from a child component back to its parent. The child component is designed to utilize various user inputs to compute a single value that needs to be returned to the parent. ...

When attempting to run a Node.js application on a Docker container, the following error may occur: "Error: Module '/usr/src/app/nodemon' not found"

Below is my Dockerfile located at the root of the nodejs application. # Building from LTS version of node (12) FROM node:12 # Creating app directory RUN mkdir -p /usr/src/app # Defining app directory inside image WORKDIR /usr/src/app # Copying package.j ...

Share a Node.js Express.js npm package for universal access within the project

Here is my current folder structure. /app.js /src /routes /controllers Within the routes folder, there are multiple javascript files that all require the passport.js package like so: const passport = require('passport'); Is it possible to c ...

How can I convert base64 data to a specific file type using React Cropper JS?

I have successfully implemented the crop functionality using react cropper js. Now, I am faced with a challenge of sending the cropped image as a file type. Currently, I can obtain the base64 string for the cropped image. However, when I submit the cropped ...