简体   繁体   English

NextJS 向内部 API 发布表单

[英]NextJS posting a form to internal API

In the Next.JS documentation I read the following.在 Next.JS文档中,我阅读了以下内容。

Note: You should not use fetch() to call an API route in getStaticProps. Instead, directly import the logic used inside your API route. You may need to slightly refactor your code for this approach.

Fetching from an external API is fine!

But if I'm not supposed to use the internal API then two questions arise.但是,如果我不应该使用内部 API,那么就会出现两个问题。

  • How can I handle POSTS?我该如何处理 POSTS? Should I handle POSTS / PUTS etc through the API but not GETS?我应该通过 API 而不是 GETS 来处理 POSTS / PUTS 等吗? That seems odd to me.这对我来说似乎很奇怪。
  • If I also should not do 'internal POSTS etc' why is the API option there?如果我也不应该做“内部帖子等”,为什么还有 API 选项?

edit:编辑:

Hmm.唔。 I suppose one of the reasons is that when using getStaticProps, and compiling a static version of the site, @ compile time the API is potentially not running.我想原因之一是在使用 getStaticProps 并编译站点的 static 版本时,@ 编译时 API 可能未运行。 But that could be easily solved by running the API at the same time.但这可以通过同时运行 API 轻松解决。 (Since GetStaticProps is not really relevant for interactive pages, so POST etc) (因为 GetStaticProps 与交互式页面并不真正相关,所以 POST 等)

edit2:编辑2:

Someone here also figure that out.这里有人也想通了。 Next.js - Error: only absolute urls are supported run export and sever separately and then you can do fetch in static props when needed. Next.js - 错误:仅支持绝对网址单独运行导出和服务器,然后您可以在需要时获取 static 道具。 Then at least all stuff is in one place.然后至少所有东西都在一个地方。

The function getStaticProps is meant to generate the data on the server-side when the page is loaded. function getStaticProps 用于在页面加载时在服务器端生成数据。

Answer 1: You should handle POST/PUT/GET, etc in your API routes.答案 1:您应该在 API 路由中处理 POST/PUT/GET 等。

Answer 2: The main difference between getStaticProps and API is the time they are run.回答 2:getStaticProps 和 API 的主要区别在于它们运行的时间。 getStaticProps is run when the page is generated on the server. getStaticProps 在服务器上生成页面时运行。 API can be called anytime you need them. API 可以在您需要时随时调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM