带有 getInitialProps 和 getStaticProps 的页面

Page with getInitialProps and getStaticProps

我有一个页面,我需要在其中使用包含凭据的 axios 获取数据,并根据 url 中的参数使用上一个请求中的数据发出另一个请求。

我不知道如何解决这个问题,因为我可以在页面中同时使用 getInitialPropsgetStaticProps,而在组件中我根本无法使用它们。

下面的代码有效,但我不知道如何分解它以便在服务器端完成登录,这样我仍然可以从 URL.

function Result({surveyId, responseId, sessionKey}) {
  return (
    <>
      <div>surveyId: {surveyId}</div>
      <div>responseId: {responseId}</div>
      <div>sessionKey: {sessionKey}</div>
    </>
  )
}

Result.getInitialProps = async ({ query }) => {
  // Example of URL
  // http://localhost:3000/result?surveyId=12345&responseId=6
  const surveyId = query.surveyId
  const responseId = query.responseId

  const data = { method: 'get_session_key', params: ['admin', 'password'], id: 1 }

  const options = { 
    headers: {
      'connection': 'keep-alive',
      'content-type': 'application/json'
    }
  }
  
  const sessionKey = await axios.post(url, data, options).then(
    (response) => {
      return response.data.result
    },
    (error) => {
      console.log(error)
    }
  )

  return { 
    surveyId: surveyId,
    responseId: responseId,
    sessionKey: sessionKey,
  }
}

getStaticPropsgetInitialPropsgetServerSideProps,它们都只在页面中执行。因为客户端向页面发出请求,所以在幕后,next.js 设置路由的方式,每当请求命中路由时,next.js 首先检查该页面是否具有任何这些功能,如果它有 运行 那些函数,首先获取结果作为道具,然后 运行 组件函数并将道具传递给组件。

getsStaticProps用于生成静态文件。一个很好的例子是博客的生成。当您 运行 npm run build 时,下一个 js 将 运行 所有 api 调用并用博客填充页面。因此,实际上,如果您检查构建文件夹,在执行 getStaticPath 的页面的 html 文件中,所有数据都已经在该 html 文件中。数据将由服务器缓存,因此当用户向这些静态生成的文件发出请求时,数据将立即提供。所以你不应该 运行 getStaticProps 中的登录过程,因为登录是一个动态过程。

所有这些功能都用于预渲染以实现更好的 SEO 优化。但是,如果您想加载特定于用户的数据,则无需为 seo 目的预呈现特定于用户的数据。你也可以做客户端。

或者您可以使用 next.js api 函数,您可以在 api 目录中编写函数,然后从 getServerSideProps 向 api 发送请求路线。这样,如果您需要 运行 不同页面中的相同代码,而不是编写相同的代码进行身份验证,您将请求 api 函数,它会为您处理。

我找到了另一个使用 getStaticPathsdynamic routes 的解决方案。就我而言 /pages/survey/[...params].js.

export default function Result({ surveyId, responseId, sessionKey }) {
  return (
    <>
      <div>surveyId: {surveyId}</div>
      <div>responseId: {responseId}</div>
      <div>sessionKey: {sessionKey}</div>
    </>
  )
}

export function getStaticPaths() {
  return { paths: [], fallback: true }
}

export async function getStaticProps({ params }) {
  const surveyId = params.survey[0]
  const responseId = params.survey[1]

  const data = { method: 'get_session_key', params: ['admin', 'password'], id: 1 }

  const options = { 
    headers: {
      'connection': 'keep-alive',
      'content-type': 'application/json'
    }
  }

  const url = 'https://example.com'
  
  const sessionKey = await axios.post(url, data, options).then(
    (response) => {
      return response.data.result
    },
    (error) => {
      console.log(error)
    }
  )

  return {
    props: { surveyId, responseId, sessionKey },
    revalidate: false,
  }
}