从 getInitialProps 向 /api 文件夹发出请求

use*_*396 0 aws-lambda next.js serverless

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

将我的应用程序成功部署到 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/usershttps://d25q7fh11ll2cg.cloudfront.net/api/users但我运行时没有域数据(即) getInitialProps

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

ngh*_*aht 5

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

首先,我建议您替换getInitialPropsgetServerSidePropsgetStaticProps确保从服务器端调用 API。

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

然后从 Next.js 文档(https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-renderinghttps://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.
Run Code Online (Sandbox Code Playgroud)

这意味着你必须重新组织你的逻辑,例如:

// 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}}
Run Code Online (Sandbox Code Playgroud)

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

我认为黑盒是大多数框架中的常见做法,并且在这个 API 路由用例中也为我们提供了帮助。