服务器引擎
在构建 Nuxt 时,我们创建了一个新的服务器引擎:Nitro。
¥While building Nuxt, we created a new server engine: Nitro.
它附带许多功能:
¥It is shipped with many features:
- 跨平台支持 Node.js、浏览器、Service Worker 等。
- 开箱即用的无服务器支持。
- API 路由支持。
- 自动代码拆分和异步加载的块。
- 适用于静态 + 无服务器站点的混合模式。
- 具有热模块重载功能的开发服务器。
API 层
¥API Layer
服务器 API 端点 和 中间件 由 Nitro 添加,其内部使用 h3。
¥Server API endpoints and Middleware are added by Nitro that internally uses h3.
主要功能包括:
¥Key features include:
- 处理程序可以直接返回对象/数组,以自动处理 JSON 响应。
- 处理程序可以返回 Promise,这些 Promise 将被等待(
res.end()
和next()
也受支持)。 - 用于主体解析、Cookie 处理、重定向、标头等的辅助函数
查看 h3 文档 了解更多信息。
¥Check out the h3 docs for more information.
:
了解更多关于 server/
目录中 API 层的信息。
¥Learn more about the API layer in the server/
directory.
::
直接 API 调用
¥Direct API Calls
Nitro 允许通过全局可用的 $fetch
助手程序调用 'direct' 路由。如果在浏览器上运行,这将向服务器发出 API 调用;如果在服务器上运行,则直接调用相关函数,从而节省额外的 API 调用。
¥Nitro allows 'direct' calling of routes via the globally-available $fetch
helper. This will make an API call to the server if run on the browser, but will directly call the relevant function if run on the server, saving an additional API call.
¥$fetch
API is using ofetch, with key features including:
- 自动解析 JSON 响应(如有需要,可访问原始响应)
- 请求正文和参数将自动处理,并使用正确的
Content-Type
标头。
更多信息,请参阅 $fetch
。
¥For more information on $fetch
features, check out ofetch.
Typed API 路由
¥Typed API Routes
使用 API 路由(或中间件)时,只要你返回值而不是使用 res.end()
发送响应,Nitro 就会为这些路由生成类型信息。
¥When using API routes (or middleware), Nitro will generate typings for these routes as long as you are returning a value instead of using res.end()
to send a response.
你可以在使用 $fetch()
或 useFetch()
时访问这些类型。
¥You can access these types when using $fetch()
or useFetch()
.
独立服务器
¥Standalone Server
Nitro 生成一个独立于 node_modules
的独立服务器版本。
¥Nitro produces a standalone server dist that is independent of node_modules
.
Nuxt 2 中的服务器不是独立的,需要 Nuxt 核心的一部分参与,例如运行 nuxt start
(使用 nuxt-start
或 nuxt
发行版)或自定义编程使用,这很脆弱,容易崩溃,不适用于无服务器和服务工作线程环境。
¥The server in Nuxt 2 is not standalone and requires part of Nuxt core to be involved by running nuxt start
(with the nuxt-start
or nuxt
distributions) or custom programmatic usage, which is fragile and prone to breakage and not suitable for serverless and service worker environments.
Nuxt 在将 nuxt build
运行到 .output
目录时生成此 dist。
¥Nuxt generates this dist when running nuxt build
into a .output
directory.
输出包含运行时代码,用于在任何环境(包括实验性的浏览器服务工作者!)中运行你的 Nuxt 服务器并提供你的静态文件,使其成为 JAMstack 的真正混合框架。此外,Nuxt 实现了原生存储层,支持多源驱动程序和本地资源。
¥The output contains runtime code to run your Nuxt server in any environment (including experimental browser service workers!) and serve your static files, making it a true hybrid framework for the JAMstack. In addition, Nuxt implements a native storage layer, supporting multi-source drivers and local assets.
:
阅读更多关于 GitHub 上 Nitro 引擎的内容。
¥Read more about Nitro engine on GitHub.
::