从 getInitialProps 请求 /api 文件夹

Request to /api folder from getInitialProps

在我的应用程序中,我将请求从 getInitialProps 发送到 api 端点(在 /api 文件夹中)。 当 运行 我的应用程序在本地主机中时,一切正常,因为它们都在同一个域 (localhost) 下。

将我的应用程序成功部署到 aws lambda 后(使用 serverless-next.js),这些请求不再有效。
原因是服务器中 运行 getInitialProps 时的主机头是 myAppBucket.s3.us-east-1.amazonaws.com,但应用程序域是 https://d25q7fh11ll2cg.cloudfront.net。 对 myAppBucket.s3.us-east-1.amazonaws.com/api/users 的请求不起作用,但对 https://d25q7fh11ll2cg.cloudfront.net/api/users 的请求有效。 但是当 运行 getInitialProps.

时我没有域数据(即 https://d25q7fh11ll2cg.cloudfront.net/api/users

我不想将域作为环境变量。还有另一种解决方案吗? 此外,直接从 getInitialProps 调用处理程序函数是有问题的,因为处理程序仅使用服务器端包。 谢谢

我遇到了和你类似的用例。

首先,我建议您将 getInitialProps 替换为 getServerSidePropsgetStaticProps 以确保您从服务器端调用 API。

getInitialProps 已弃用,它们可能 运行 在 客户端 服务器端 ,因此它们可能导致您的用例发生意外行为(我们的 api 路由是服务器端)

然后从 Next.js 文档 (https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering or https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation),检查他们的小灰框:

Note: You should not use fetch() to call an API route in your application. 
Instead, directly import the API route and call its function yourself. 
You may need to slightly refactor your code for this approach.

这意味着您必须 re-organize 您的逻辑类似于:

// A naive axample

pages
  api
    route1.js
      export async function service1()
      export default async function handler(req,res)
        const result = await service1()
        res.json(result);

  my_page.js
    getStaticProps/getServerSideProps
      const result = await import("./api/route1").then(mod => mod.service1());
      return {props: {result}}

是的,只需将您的逻辑分解为一个黑盒 (service1) 并将它们与 API 路由的默认处理程序一起导出。

我认为 blackbox 是大多数框架中的常见做法,并且在这个 API 路由用例中也对我们有帮助。