Encountering an undefined response in API call using Fetch with Express Nuxt

I've hit a roadblock with a task involving Express, API, and Fetch. I'm utilizing Nuxt along with Shopify API endpoints to retrieve data such as orders.

Below is my express API Endpoint which should return an array of objects (orders).

const bodyParser = require('body-parser')
const app = require('express')()
const axios = require('axios')

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

// Rest of the code...

In my Nuxt store.js file, I am using fetch to send a post request to the endpoint mentioned above.

async function apiPost(endpoint, { data }) {
  // Code snippet for making POST request...
}

When logging res.json(), it returns a promise.

https://i.sstatic.net/H18Uo.png

Despite being a promise, I tried to see the results anyhow.

// Code snippet for handling the promise returned by res.json()...

The results from the response end up being an array of objects.

https://i.sstatic.net/odH3t.png

The issue arises when trying to properly return this object as 'orderResponse' always remains undefined!

Here's a snippet where the 'apiPost' function is called with the 'endpoint'. However, regardless of the attempts made, 'orderResponse' stays undefined.

async fetchOrders({ state, dispatch, commit }, payload) {
    try {
      const ordersResponse = await apiPost('/customer-orders', {
        data: { customerID: state.customer.id }
      })

      console.log('ordersResponse', ordersResponse) // **undefined**
    } catch (error) {
      console.error(error)
      throw error
    }
  }

Any assistance would be greatly appreciated.

Answer №1

Upon inspection, it appears that the apiPost function should include a return statement within the 'application/json' if condition.

if (contentType.startsWith('application/json')) {
      return res.json()
    }

After implementing this change, you can expect to receive data when using the ordersResponse variable.

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

Alignment of Bootstrap thumbnails in a horizontal layout

After adding the thumbnail class to my thumbnails div, I noticed that some of the thumbnails were smaller in size than others. Wanting them all to have the same height, I decided to give each thumbnail a fixed height of 210px. However, this caused the sm ...

Utilizing Jquery Plugins in Node.js with ES6 Imports: A Comprehensive Guide

I recently started using a jQuery calendar plugin, which can be found at this link: . I have been utilizing it with a CDN, but now I am looking to incorporate it as a Node.js module. What would be the most effective method to achieve this? Edit: Just to ...

Challenges with differentiating between addition and concatenation in Vue computed properties

Recently diving into Vue and came across an intriguing issue, I am curious to know the reason behind it and how to prevent it. <template> <div> <input type="number" v-model="a" style="color: white" /> <input type="number" v- ...

What is the best way to add a constant value to all objects within an array without having to iterate through each one

Is there a more concise way to add a fixed value to each object in an array without using a loop in JavaScript? Programming Language used: JavaScript Example Array: "cars": [ { "name":"Ford", "models":"Fiesta" }, { "name":"BMW", "models":"X1" }, ...

Accessing server API through Java programming language with JSON integration

I have found server API documentation with various methods, but I lack experience in utilizing APIs for server interaction. Can anyone suggest an easier approach to make use of it? Snippet from API Documentation: Method "Login": POST Parameters: em ...

Triggering an Ajax request by clicking on a link

In the scenario where you have a specific word on a webpage that you would like to trigger an onclick event and initiate an ajax request, what is the best approach to accomplish this? ...

Understanding the use of "el" in a function parameter in Vue Js

I am new to VueJS, so please be patient with me. I am trying to code a function that will scroll to an element with a specific ID when a "?" is used in the URL. I want it to have the same effect as demonstrated here. My assignment requires me to follow a ...

passport not initializing session with requests

I am currently utilizing passportJS for managing login and persistent sessions on the server backend. While everything functions properly when sending requests from the server frontend (a webpage that I didn't create and lack sufficient knowledge to ...

Use React to insert a leading zero next to a number in the input field if the number is greater than 10

I have scoured the web and consulted resources like this one but haven't found a solution that addresses my specific issue with adding padding to input numbers. My goal is to automatically add a leading zero whenever the number inside an input field i ...

Save a version identifier in already deployed Redux stores for production settings

I am seeking a way to introduce a new bundle into a live React/Redux application that caters to users who are already logged in with a different state tree. To achieve this, I intend to prompt the logged-in users to logout so that I can reset the state tre ...

Instructions for correctly integrating the ng2-datepicker module into an Angular 2 application

Ng2-datepicker (1.0.6) Angular2 (2.0.0-rc.5) As I attempted to implement it in my HTML following the documentation, I encountered the following error: zone.js:484 Unhandled Promise rejection: Template parse errors: Can't bind to 'ngMode ...

Need help accessing data from an API using Axios.post and passing an ID?

Can someone help me with passing the ID of each item using Axios.Post in order to display its data on a single page? The image below in my Postman shows how I need to send the ID along with the request. Additionally, I have the first two URL requests for t ...

How to convert deeply nested object structures containing arrays in JavaScript

Despite the less-than-desirable name of this inquiry, the question is fairly straightforward. I have a particular object: let test = { date1: [ { time: 1, value: 5, }, { time: 2, value: 6, }, ], date2: [ { ...

Switch the menu state to closed when we click outside of it while it's open

I'm currently working on a scenario involving a menu that toggles when a button is clicked. The issue I'm facing is that when I click on the menu button, it opens correctly. However, the problem arises with the following code: Whenever I click ...

Unable to retrieve the error message from the error object

In my express app, I have the following line of code: catch (err) { res.status(500).send(err.message); } Upon logging the error, I am presented with this message: name: 'TokenExpiredError', message: 'jwt expired', How ...

Vue instance with non-reactive data

I am looking to store an object in Vue that will be accessible throughout the entire instance but does not need to be reactive. Typically, if I wanted it to be reactive, I would use 'data' like this: new Vue({ data: myObject }) However, since ...

Retrieving the value from a vuetify v-text-field to use in another text field

Looking to suggest a username based on the user's first and last name. The concept is that after the user fills out the first name and last name fields, the value in the username field will be a combination of their first and last names. firstName = B ...

How can I make a basic alert box close after the initial click?

After clicking a button, I have a simple jQuery script that triggers a fancybox. However, the issue is that the fancy box does not close after the first click of the button; it only closes after the second click... Another problem arises inside the fancy ...

What steps can I take to resolve the spawn unknown error when using npx create-next-app in Visual Studio Code (VSCode)?

Every time I attempt to create a new app using either vscode or cmd, I encounter a spawn unknown error. The error message says "Aborting installation. Unexpected error. Please report it as a bug: Error: spawn UNKNOWN". Unfortunately, the installation abo ...

Utilize the power of AJAX and Laravel to seamlessly upload an Excel file

I am currently facing an issue with importing an Excel file using AJAX and Laravel in my application. The form of excel import is embedded within another form and I have observed that the error handling is not displaying the error messages correctly on the ...