"Conducting API calls in NextJS: Why is Axios/Fetch returning incorrect results when using the post

I'm trying to use a post method on an API, but for some reason when I call the function it posts to the wrong path of the API.

Here is the script I am using for the post:

 //Creating Order
  const createOrder = async (data) => {
    try {
      const res = await axios.post(
        `${process.env.API_ROOT}/api/orders` ||
          `${process.env.LOCAL_URL}/api/orders`,
        data
      );
      if (res.status === 201) {
        router.push(`/api/orders/${res.data._id}`);
        dispatch(reset());
      }
    } catch (err) {
      console.log(err);
    }
  };

I call this function when approving from Paypal and using the order button. However, when I press the button, the URL of the API path changes to something like

${process.env.API_ROOT}/undefined/api/orders 
or
${process.env.LOCAL_URL}/undefined/api/orders
. What could be causing this problem?

https://i.stack.imgur.com/BbzaW.png

But when I use something like this, it works fine:

//Creating Order
  const createOrder = async (data) => {
    try {
      const res = await axios.post(`/api/orders`, data);  <=====  It's working
      if (res.status === 201) {
        router.push(`/api/orders/${res.data._id}`);
        dispatch(reset());
      }
    } catch (err) {
      console.log(err);
    }
  };

Answer №1

When working on the front-end part of the code, it's important to note that if your process.env.API_ROOT returns undefined, there is a workaround using process.env variables in frontend code. Just remember to prefix them with NEXT_PUBLIC as shown below:

process.env.NEXT_PUBLIC_LOCAL_URL
process.env.NEXT_PUBLIC_API_ROOT

For more information, check out the official documentation

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

Maintaining a consistent style input until it is modified

I'm currently dealing with this code (continuing from a previous question): input[type=submit]:focus { background-color: yellow; outline: none; } The issue I'm facing is that when I click anywhere else on the screen, the background color go ...

`In TypeScript Angular, encountering challenges with accessing object properties`

My TypeScript object looks like this const playlist: { tracks: Array<Track> } = { tracks: new Array<Track>() }; This is the Track interface I am working with interface Track { title?: string; album?: string; artists?: string; duration? ...

Issue with margins of sections when attempting to activate menu class while scrolling

My Objective: I want to create a website where the menu highlights the section that is currently being viewed as the user scrolls up and down. Progress So Far: I have successfully implemented a functioning menu that changes to "active" when the correspo ...

Creating a pattern for values ranging from 18 to 99, including leading zeros, using regular expressions

Looking for a Regular Expression that matches numbers from 018 to 099, inclusive. The numbers must range between 18 and 99, and include a leading zero for values less than 100. ...

Navigating with Angular/Routing through Dynamic Content

Exploring the best approach for managing dynamic content within an angular application has been my recent focus. Currently, I have an array containing phone numbers and aim to organize them based on their respective countries. For instance, all German phon ...

Issue encountered while resolving npm dependencies: ERESOLVE error due to conflicting React versions

Encountered an issue while attempting to host my website on Vercel: Error! Unable to resolve dependencies: npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="_ ...

Strategies for Implementing Multi-Step Password Form Validation

Currently, I am using https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_form_steps as the foundation of my form with some adjustments. Validation is functioning correctly where empty fields disable the next button. However, when I attempt to add ...

How can the background color of a DIV be altered based on the values of an array's minimum

Basically, I am fetching values from an array using AJAX. The background color will change from green to red based on the "aht_value". Currently, the colors are displaying correctly because I hardcoded the values in the calculation below. However, I want t ...

Using the set method to assign identical values within a Record object results in the creation of a distinct new

I have implemented Immutable Record in ReduceStore to prevent emitting changes when there is no actual data change. However, I am facing an issue where even for the same data, Immutable.js creates a new object causing the ReduceStore `areEqual` function to ...

Obtain redirected JSON data locally using Angular 5

Currently, I am working on retrieving JSON data which will be sent to my localhost through a POST method. The SpringBoot API controller will validate the JSON content before forwarding it to my localhost. My task is to intercept this JSON data when it is t ...

Exploring the functionalities of AngularJS' ng-options when working with select elements

In my search through other posts, I came across this issue but couldn't find a solution. Here is the array in question: $scope.items = [ {ID: '000001', Title: 'Chicago'}, {ID: '000002', Title: 'New York' ...

Step-by-step guide on resolving AngularJS Issue: [$injector:modulerr]

I'm encountering an issue with Angular JS where I'm receiving the following error: jquery.js:7993 Uncaught Error: [$injector:modulerr] Failed to instantiate module application due to: Error: [$injector:nomod] Module 'application' is no ...

Having trouble displaying HTML UL content conditionally in Reactjs?

My goal is to display a list of items, limited to a maximum of 5 items, with a "more" button that appears conditionally based on the number of items in the list. However, I am encountering an issue where passing in 5 li items causes them to be rendered as ...

Checking connectivity in an Ionic application

Within my Ionic application, I am faced with the task of executing specific actions depending on whether the user is currently connected to the internet or not. I plan on utilizing the $cordovaNetwork plugin to determine the connectivity status within the ...

Which is better for privacy: underscored prototype properties or encapsulated variables?

There's something that's been on my mind lately - it seems like people are aware of something that I'm not. Let's take a look at an example in FOSS (simplified below)... When creating a class in JavaScript, I personally prefer Crockford ...

What is the best way to save the output of a middleware in express js so that it can be conveniently accessed by the rest of the

Currently, I am working with a middleware that returns an object. My goal is to save this object so that other parts of the application can utilize the data it contains. How can I achieve this? This snippet is from my app.js file: import { myMiddlewareFun ...

Updating multiple collections in MongoDBRestructuring data across multiple

Imagine a scenario where an API call must update two different collections. It's crucial that if one update fails, the first update needs to be reverted. How can I guarantee that both operations either complete successfully or none at all? Let me prov ...

What is the process for displaying HTML page code received from an AJAX response?

My current project involves implementing JavaScript authentication, and I have a specific requirement where I need to open an HTML file once the user successfully logs in. The process involves sending an AJAX request with the user's username and passw ...

"Mastering the art of passing variables within the index parameter for JavaScript push method

I need help passing a variable inside index in JavaScript push while working with Angular. Here is my current code: angular.forEach(Val, function (Value,Key) { angular.forEach(Value, function (Value1,Key1) { saveDetailArr.push({ 'option_i ...

What is the process of integrating ES6 modules with app.get in a Node/Express routing application?

After researching the benefits of ES6 export, I made the decision to implement it in a NodeJS/Express project instead of using module exports. The MDN documentation explained that export is used as shown below: export function draw(ctx, length, x, y, color ...