0

我在 getServerSideProps 函数中的 http axios api 数据获取尝试总是返回错误。我成功地从 cockies 中恢复了令牌和 userId,并尝试将它们作为参数传递以进行服务器 api 调用。

export const getServerSideProps: GetServerSideProps = async (ctx) => {

        try {
        const { userId, token } = ctx.req.cookies; 
        // console.log(userId)      
        // console.log(token)               
           
            const res = await api.get(`/users/show/${userId}`, {
              headers: { token },
         
            })
          console.log(res.data)
            const userData  = res.data;      

          if (!userData) {
            return {
              notFound: true,
            }
          }
          
            return {
              props: {  
                userData
         
              }
            }
          
        } catch (error) {
          return error
        }
          
          
      }

并不断收到相同的错误:

  Server Error
Error: Additional keys were returned from `getServerSideProps`. Properties intended for your component must be nested under the `props` key, e.g.:

    return { props: { title: 'My Title', content: '...' } }

Keys that need to be moved: config, request, response, isAxiosError, toJSON.

4

1 回答 1

1

返回的对象应该总是在路上

return { props: {//在此处添加您的对象} }

export const getServerSideProps: GetServerSideProps = async (ctx) => {

        try {
        const { userId, token } = ctx.req.cookies; 
        // console.log(userId)      
        // console.log(token)               
           
            const res = await api.get(`/users/show/${userId}`, {
              headers: { token },
         
            })
          console.log(res.data)
            const userData  = res.data;      

          if (!userData) {
            return {
              return { props: { notFound: true } },
            }
          }
          
            return {
              props: {  
                userData
         
              }
            }
          
        } catch (error) {
          return { props: {} }
        }
          
          
      }
于 2021-10-22T01:47:54.220 回答