带有 getInitialProps 和 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 首先检查此页面是否具有这些功能,如果有它首先运行这些函数,将结果作为 props 获取,然后运行组件函数并将 props 传递给组件。

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,sessionKey },revalidate: false,}
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...