我是NextJS的新手。我正在编写一个简单的页面,其中我需要从我的后端应用程序中检索数据。我的后端应用程序是一个完全独立的应用程序,用go编写。我的缺点是,我必须使用getServerSideProps从负载中的服务器获取数据,因此我得到了以下内容:
myProject/pages/category/new.js
export default function AddNewCategory(data) {
...
}
export const getServerSideProps = async () => {
const data = await getAllCategories();
console.log(await data)
return {
props: {
data: { data }
}
};
};myProject/api/category.js
import axios from "axios";
// getAllCategories returns a list of all active categories
export const getAllCategories = async() => {
axios.get("http://127.0.0.1:8080/api/v1/categories")
.then(function (response) {
console.log(response.data)
return response.data;
})
.catch(error => {
console.error("error")
console.log(error)
})
}如您所见,我在getAllCategories中有一个print语句,它打印:
{
data: [
{
id: 1,
name: 'Pop',
slug: 'pop',
description: 'Pop',
parent: 0,
active: true,
created_at: '2022-05-03T19:50:00-04:00',
updated_at: '2022-05-03T19:50:00-04:00',
deleted_at: null
},
{
id: 3,
name: 'Pop 2',
slug: 'pop-2',
description: 'Pop',
parent: 0,
active: true,
created_at: '2022-05-03T19:50:24-04:00',
updated_at: '2022-05-03T19:50:24-04:00',
deleted_at: null
}
]
}然而,我得到了以下错误:
错误-错误:在“/
getServerSideProps/new”中序列化从getServerSideProps返回的错误。原因:undefined不能序列化为JSON。请使用null或省略此值。
我看到,我应该尝试将数据转换为string,然后返回到json:
return {
props: {
data: JSON.parse(JSON.stringify(data))
}
};但是当我这样做的时候,我得到了一个不同的错误:
错误- SyntaxError: JSON中位于0位置的意外令牌u
我用的是next@12.1.5
知道怎么回事吗?
发布于 2022-05-07 07:11:04
我认为您必须使用.json()将json转换为javascript对象。以下代码来自nextjs文档。
export async function getServerSideProps() {
// Fetch data from external API
const res = await getAllCategories();
const data = await res.json()
// Pass data to the page via props
return { props: { data } }
}编辑
在这种情况下,不需要添加const data = await res.json(),因为请求是通过axios发出的,在axios中,响应已经被用作javascript对象,因此不需要解析。
https://stackoverflow.com/questions/72149482
复制相似问题