首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NextJS:序列化从‘`getServerSideProps`’返回的`.data.data`时出错

NextJS:序列化从‘`getServerSideProps`’返回的`.data.data`时出错
EN

Stack Overflow用户
提问于 2022-05-07 04:23:54
回答 1查看 791关注 0票数 1

我是NextJS的新手。我正在编写一个简单的页面,其中我需要从我的后端应用程序中检索数据。我的后端应用程序是一个完全独立的应用程序,用go编写。我的缺点是,我必须使用getServerSideProps从负载中的服务器获取数据,因此我得到了以下内容:

myProject/pages/category/new.js

代码语言:javascript
复制
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

代码语言:javascript
复制
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语句,它打印:

代码语言:javascript
复制
{
  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:

代码语言:javascript
复制
return { 
  props: { 
    data: JSON.parse(JSON.stringify(data)) 
  } 
};

但是当我这样做的时候,我得到了一个不同的错误:

错误- SyntaxError: JSON中位于0位置的意外令牌u

我用的是next@12.1.5

知道怎么回事吗?

EN

回答 1

Stack Overflow用户

发布于 2022-05-07 07:11:04

我认为您必须使用.json()将json转换为javascript对象。以下代码来自nextjs文档

代码语言:javascript
复制
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对象,因此不需要解析。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72149482

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档