【问题标题】:Getting undefined in API call via Fetch - Express Nuxt通过 Fetch 在 API 调用中获取未定义 - Express Nuxt
【发布时间】:2021-06-23 14:44:49
【问题描述】:

我非常卡在使用 Express、API、Fetch 的任务上。

我正在使用 Nuxt + Shopify API 端点来获取数据,例如下面的订单

这是我的快速 API 端点。 结果应该返回一个对象数组(订单)

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

现在,在我的 Nuxt store.js 中,我使用 fetch 向上面的那个端点发出 post 请求。

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()
    }
  })
}

当我 console.log res.json() 时,这是一个承诺

既然是承诺,我还是想看看结果如何。

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

原来剩下的是一个对象数组。

但是,我不知道如何正确返回此对象,因为下面的“ordersResponse”始终未定义!

下面是一个调用 apiPost 的函数,传入 'endpoint'。但是,orderResponse 是未定义的。我已经尝试过解决方案,但所有这些最终都是未定义的 orderResponse。

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
    }
  },

感谢任何帮助

【问题讨论】:

    标签: javascript api express nuxt.js


    【解决方案1】:

    看起来apiPost 函数需要从 'application/json' if 块中返回。

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

    然后,您应该在为 ordersResponse 变量调用它时接收回数据。

    【讨论】:

      猜你喜欢
      • 2019-03-11
      • 2018-07-04
      • 2021-12-24
      • 1970-01-01
      • 1970-01-01
      • 2020-08-03
      • 2021-01-21
      • 2019-10-13
      • 2022-01-18
      相关资源
      最近更新 更多