在我的应用中,我正在从getInitialProps
向api端点(在/ 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/users
的请求有效。
但是运行https://d25q7fh11ll2cg.cloudfront.net/api/users
时我没有域数据(即getInitialProps
)。
我不想将域作为环境变量。有另一种解决方案吗?
另外,直接从getInitialProps
调用处理程序函数也是有问题的,因为处理程序仅使用服务器端程序包。
谢谢
答案 0 :(得分:1)
我和您一起遇到类似的用例。
首先,建议您将getInitialProps
替换为getServerSideProps
或getStaticProps
,以确保您从服务器端调用API。
getInitialProps
已过时,它们可能在客户端或服务器端上运行,因此它们可能会导致您的用例发生意外行为(我们的api路由为服务器端)
然后从Next.js文档(https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering或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.
这意味着您必须重新组织逻辑,例如:
// 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路由的默认处理程序一起导出即可。
我认为黑盒是大多数框架中的常见做法,并且也可以帮助我们解决此API路由用例。