Next.JS:如何在服务器端发出所有请求
我正在构建一个 Next.JS 应用,该应用将从Python API和一个Postgres数据库.
I am building a Next.JS app that will be getting data from a Python API and an Postgres Database.
通常这很简单,除非要求是这样,我需要从服务器端而不是用户客户端发送所有请求.
Normally this would be simple, except requirements are such that I need to send all requests from the server-side, not the user's client.
我一直在使用并浏览 getInitialProps
,但是由于README
:
I have been working with and grokking getInitialProps
, but I am not confident that it is the full solution that I need because of this line in the README
:
对于初始页面加载,
getInitialProps
仅在服务器上执行.getInitialProps
仅在通过Link组件或使用路由API导航到其他路由时在客户端上执行.
For the initial page load,
getInitialProps
will execute on the server only.getInitialProps
will only be executed on the client when navigating to a different route via the Link component or using the routing APIs.
getInitialProps
似乎是为初始页面加载而设计的,而不是为随后的服务器端数据获取而设计的.
It seems that getInitialProps
is designed for the initial page load, and not for subsequent server-side data fetching.
如何设计Next.JS应用程序,使所有请求都来自服务器端?
How can I design my Next.JS app in such a way that all requests come from the server-side?
注意:
- 可以肯定的是,每个请求都会导致初始页面加载.
- 用户Client可以与Node(Next.JS)服务器对话,因为它是公开的.我目前正在尝试将Next.JS包装在快递服务器中.
请提前寻求帮助
我通过在Express中包装Next.JS找到了解决方案!
I found a solution by wrapping Next.JS in Express!
我已将一个简单的示例项目推送到GitHub 此处
I have pushed a simple example project to GitHub here
该仓库具有良好的自述文件以及代码中的注释,详细说明了正在发生的事情.
The repo has a nice README as well as comments in the code that detail what's going on.
快速下载:
- 在一个快速服务器中包装Next.JS.通过调用
nextApp.render(...)
显式呈现页面,这在标准Next.JS应用程序中隐式发生.参见 server.js - 使用快速路由.在使用
nextApp.render(...)
呈现页面之前发出服务器端请求.参见 server.js . - 使用标准锚标记来确保页面请求命中快递服务器.参见 index.js
-
nextApp.render
使用getInitialProps
的上下文(ctx
)参数将传递的值提供给页面.您可以通过在getInitialProps
中返回它们来使这些值在页面this.props
中可用.参见 stars.js
- Wrap Next.JS in an express server. Explicitly render pages by calling
nextApp.render(...)
which happens implicitly in standard Next.JS apps. See server.js - Use express routing. Make server-side requests prior to rendering the pages with
nextApp.render(...)
. See server.js. - Use standard anchor tags to ensure that pages requests hit the express server. See index.js
-
nextApp.render
provides passed values to the page in the context (ctx
) parameter ofgetInitialProps
. You can make these values available in the pagesthis.props
by returning them ingetInitialProps
. See stars.js
建议和改进!