Next.JS:如何在服务器端发出所有请求

编程入门 行业动态 更新时间:2024-10-28 14:26:16
本文介绍了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

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

建议和改进!

更多推荐

Next.JS:如何在服务器端发出所有请求

本文发布于:2023-11-26 14:25:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634127.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:服务器端   如何在   JS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!