---
title: "服务器引擎"
description: "Nuxt 由一个新的服务器引擎驱动：Nitro。"
canonical_url: "https://nuxt.zhcndoc.com/docs/4.x/guide/concepts/server-engine"
---
# 服务器引擎

> Nuxt 由一个新的服务器引擎驱动：Nitro。

在构建 Nuxt 时，我们创建了一个新的服务器引擎：[Nitro](https://nitro.zhcndoc.com/)。

它提供了许多功能：

- 支持跨平台运行，包括 Node.js、浏览器、服务工作者等。
- 开箱即用的无服务器支持。
- 支持 API 路由。
- 自动代码拆分和异步加载代码块。
- 静态 + 无服务器站点的混合模式。
- 带有热模块重载的开发服务器。

## API 层

Nitro 添加了服务器 [API 端点](https://nuxt.zhcndoc.com/docs/4.x/directory-structure/server#server-routes) 和 [中间件](https://nuxt.zhcndoc.com/docs/4.x/directory-structure/server#server-middleware)，其内部使用 [h3](https://github.com/h3js/h3)。

主要特性包括：

- 处理器可以直接返回对象或数组，自动处理 JSON 响应
- 处理器可以返回 Promise，支持 await （同时支持 `res.end()` 和 `next()`）
- 提供请求体解析、Cookie 处理、重定向、请求头等辅助函数

更多信息请查阅 [h3 文档](https://github.com/h3js/h3)。

::read-more{to="https://nuxt.zhcndoc.com/docs/4.x/directory-structure/server#server-routes"}
了解有关 `server/` 目录中 API 层的更多信息。
::

## 直接 API 调用

Nitro 允许通过全局可用的 [`$fetch`](https://nuxt.zhcndoc.com/docs/4.x/api/utils/dollarfetch) 辅助函数“直接”调用路由。如果在浏览器上运行，它会向服务器发起 API 调用；如果在服务器上运行，则会直接调用相关函数，**省去一次额外的 API 调用**。

[`$fetch`](https://nuxt.zhcndoc.com/docs/4.x/api/utils/dollarfetch) API 使用 [ofetch](https://github.com/unjs/ofetch)，其主要特性包括：

- 自动解析 JSON 响应（也可访问原始响应）
- 自动处理请求体和参数，并设置正确的 `Content-Type` 头

有关 `$fetch` 的更多功能信息，请参考 [ofetch](https://github.com/unjs/ofetch)。

## 类型化 API 路由

使用 API 路由（或中间件）时，只要返回值而非使用 `res.end()` 发送响应，Nitro 会为这些路由生成类型定义。

使用 [`$fetch()`](https://nuxt.zhcndoc.com/docs/4.x/api/utils/dollarfetch) 或 [`useFetch()`](https://nuxt.zhcndoc.com/docs/4.x/api/composables/use-fetch) 时，可以访问这些类型。

## 独立服务器

Nitro 生成一个独立的服务器构建（dist），不依赖 `node_modules`。

Nuxt 2 的服务器不是独立的，运行 `nuxt start` 时需要 Nuxt 核心的一部分（使用 [`nuxt-start`](https://www.npmjs.com/package/nuxt-start) 或 [`nuxt`](https://www.npmjs.com/package/nuxt) 发布包）或自定义编程方式，这种方式脆弱且容易出错，不适合无服务器和服务工作者环境。

运行 `nuxt build` 时，Nuxt 会将此 dist 生成到 [`.output`](https://nuxt.zhcndoc.com/docs/4.x/directory-structure/output) 目录中。

输出包含运行 Nuxt 服务器的运行时代码，可以适配任何环境（包括实验性的浏览器服务工作者！）并托管静态文件，使其成为 JAMstack 的真正混合框架。此外，Nuxt 还实现了原生存储层，支持多源驱动和本地资源。

::read-more{icon="i-simple-icons-github" to="https://github.com/nitrojs/nitro" target="_blank"}
在 GitHub 上阅读有关 Nitro 引擎的更多信息。
::


## Sitemap

See the full [sitemap](https://nuxt.zhcndoc.com/sitemap.md) for all pages.
