Next.JS:如何在服务器端发出所有请求 [英] Next.JS: How to make ALL requests server-side

查看:783
本文介绍了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?

注意:

请提前寻求帮助

推荐答案

我通过在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 of getInitialProps. You can make these values available in the pages this.props by returning them in getInitialProps. See stars.js

建议和改进!

这篇关于Next.JS:如何在服务器端发出所有请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆