Getting undefined in API call via Fetch - Express Nuxt

Viewed 379

I am extremely stuck on a task using Express, API, Fetch.

I am using Nuxt + Shopify API endpoints to grab data such as orders like below

This is my express API Endpoint. The results 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())

app.post('/getJSON', async (req, res) => {
  const { customerID } = req.body

  const id = Buffer.from(customerID, 'base64')
    .toString('binary')
    .split('gid://shopify/Customer/')
    .pop()
  console.log('id is', id)

  const endpoint = `https://test.myshopify.com/admin/api/2020-07/customers/${id}/orders.json`

  try {
    const response = await axios.get(endpoint, {
      headers: {
        'Content-Type': 'application/json',
        'X-Shopify-Access-Token': '*****************'
      }
    })

    res.status(200).json(response.data.orders)
  } catch (error) {
    res.status(500).send(error)
  }
})

module.exports = app

Now, in my Nuxt store.js, I am using fetch to make a post requests to that endpoint above.

async function apiPost(endpoint, { data }) {
  await fetch(`/api${endpoint}/getJSON`, {
    method: 'POST',
    body: JSON.stringify(data),
    headers: {
      'Content-Type': 'application/json'
    }
  }).then(async (res) => {
    const contentType = res.headers.get('content-type')

    if (contentType.startsWith('text/html')) {
      return res.text()
    }

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

When I console.log res.json(), it is a promise

enter image description here

Since it is a promise, I wanted to see what the results were anyways.

res.json().then((resp) => {
    console.log('resp is', resp)
})

Turns out the rest is an array of objects.

enter image description here

However, I do not know how to return this object correctly, as the "ordersResponse" below is always undefined !

Below is a function calling the apiPost passing in the 'endpoint'. However, the orderResponse is undefined. I have tried solutions, but all of them end up as orderResponse being 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 help is appreciated

1 Answers

It looks like the apiPost function needs to make a return from within the 'application/json' if block.

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

You should then receive data back when calling it for the ordersResponse variable.

Related