【发布时间】: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