我在Nuxt和服务器端渲染我的产品时遇到了一些问题。因此,我正在尝试将我的数据方法转换为asyncData。然而,事情并没有按计划进行。我不确定我的问题是什么。
这段代码可以工作,但没有asyncData。
export default {
components: {
CldImage,
CldTransformation,
CollectionHeader,
Loading,
Footer
},
head() {
return {
title: this.title,
meta: [
{ hid: 'description', name: 'description', content: 'lorem ipsum' }
]
}
},
data: () => ({
cloudinaryCloudName: process.env.cloudinaryCloudName,
popularProducts: [],
loadingPopularProducts: false,
title: 'website.com'
}),
mounted() {
this.loadingPopularProducts = true
axios.get('/api/v1/products?popular=true&limit=6').then((response) => {
this.popularProducts = response.data.results
this.loadingPopularProducts = false
})
}
}这是我在asyncData的go,但我收到了catch "Products not found“。
export default {
components: {
CldImage,
CldTransformation,
CollectionHeader,
Loading,
Footer
},
head() {
return {
title: this.title,
meta: [
{ hid: 'description', name: 'description', content: 'lorem ipsum' }
]
}
},
data: () => ({
cloudinaryCloudName: process.env.cloudinaryCloudName,
loadingPopularProducts: false,
title: 'website.com'
}),
asyncData({ params, error }) {
return axios.get('/api/v1/products?popular=true&limit=6')
.then(response => {
const popularProducts = response.data.results
return { popularProducts }
})
.catch((e) => {
error({ statusCode: 404, message: 'Products not found' })
})
}
}如果没有捕获,我会得到这个错误
(node:14916) UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED 127.0.0.1:80
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1054:14)
(node:14916) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 26)发布于 2020-01-16 17:07:22
感谢您的回答。我让一个朋友看了一下,这就是对我有效的结果。
async asyncData(context) {
const url = '/api/v1/products?popular=true&limit=8'
const data = await context.app.getAsyncData(url)
return { popularProducts: data.results ? data.results : [] }
}只是想把答案贴出来。
https://stackoverflow.com/questions/59256990
复制相似问题