NextJS 错误:你的 `getServerSideProps` 函数没有返回一个对象

时间:2021-02-10 19:52:39

标签: node.js postgresql heroku next.js vercel

我有一个类似 reddit 的应用程序。带有 postgres db 的 node/express TypeORM 服务器位于 heroku 上。带有 nextJS 的客户端在 vercel 上。注册、评论、upvote/downvote 工作正常。当我尝试创建一个新社区时,我得到了一个

502: BAD_GATEWAY
Code: NO_RESPONSE_FROM_FUNCTION
ID: cdg1::lrlvg-1612986052014-c0b0a2cd09ac

错误。

在 vercel 函数日志中或在终端的 PC 上,我收到一个错误:您的 getServerSideProps 函数没有返回对象。您是否忘记添加 return

代码:

export const getServerSideProps: GetServerSideProps = async ({ req, res }) => {
  try {
    const cookie = req.headers.cookie
    if (!cookie) throw new Error('Missing auth token cookie')

    await Axios.get('/auth/me', { headers: { cookie } })

    return { props: {} }
  } catch (err) {
    res.writeHead(307, { Location: '/login' }).end()
  }
  
}

编辑:当我在 PC 上运行客户端和服务器时,它可以工作,但在部署时出现上面发布的错误。

2 个答案:

答案 0 :(得分:0)

捕获不会返回。你可以这样做

res.writeHead(307, { Location: '/login' }).end()
return { props: {ok: false, reason: "some error description for your own consumption, not for client side"}

同样,在try块里面,也许你也想通过res.writeHead(200)向服务器推送一些数据?

我不太清楚为什么成功时将数据作为函数返回值返回,失败时通过 HTTP 发送错误。我认为这可能是你的失败点,双方应该要么返回 HTTP,要么返回一个函数返回值,或者两者都返回,但不是一个一个,另一个一个。

答案 1 :(得分:0)

从 Next.js 10 开始,getServerSideProps 支持为此确切目的返回 redirect 对象 - 这也解决了您通过显式返回对象而遇到的错误。

export const getServerSideProps: GetServerSideProps = async ({ req, res }) => {
    try {
        const cookie = req.headers.cookie
        
        if (!cookie) throw new Error('Missing auth token cookie')

        await Axios.get('/auth/me', { headers: { cookie } })

        return { props: {} }
    } catch (err) {
        // Handle error

        return {
            redirect: {
                destination: '/login',
                statusCode: 307
            }
        }
    }
}