This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index or append .md to any documentation URL.
Expo 服务器
用于 Expo Router 项目的服务器端 API 和运行时。
expo-server 是用于 Expo Router 的服务器端 API 和运行时库。它提供了一些可在你的 Expo Router API 路由或其他服务器代码中使用的辅助工具,并包含用于运行 Expo Router 服务器导出的适配器。
安装
🌐 Installation
要在你的项目中使用 expo-server,你需要将你的 Expo Router 项目配置为以 server 模式导出。请按照 Expo Router 的 API 路由指南中的说明操作:
🌐 To use expo-server in your project, you need to configure your Expo Router project to export in server mode. Follow the instructions from Expo Router's API Routes guide:
了解如何使用 Expo Router 创建服务器端点。
用法
🌐 Usage
expo-server 的运行时 API 只能在服务器端代码中使用,并且可以让你访问服务器端的运行时环境。运行时 API 提供的函数可以在请求处理程序的异步上下文中调用,并且可以让你获取当前请求的信息或安排与传入请求并发运行的任务。
访问请求元数据
🌐 Accessing request metadata
import { origin, environment } from 'expo-server'; export async function GET() { return Response.json({ isProduction: environment() == null, isStaging: environment() === 'staging', origin: origin(), }); }
安排任务
🌐 Scheduling tasks
import { runTask, deferTask } from 'expo-server'; export async function GET() { runTask(async () => { console.log('will run immediately.'); }); deferTask(async () => { console.log('will run after the response resolved.'); }); return Response.json({ success: true }); }
适配器
🌐 Adapters
expo-server 提供了适配器,用于在不同环境或不同云提供商的无服务器函数上运行 Expo Router 的服务器端导出。通常,每个运行时都需要其自己的适配器,以便与 expo-server 运行时配合使用。在将应用部署到这些提供商之前,熟悉 npx expo export 命令的基础知识会很有帮助。
要学习如何在不同的第三方服务上托管 API 路由,请按照 Expo Router 的 API 路由指南中的说明操作:
🌐 To learn how to host API routes on different third-party services, follow the instructions from Expo Router's API Routes guide:
学习如何在第三方服务上托管 API 路由。
按照惯例,所有适配器都会导出一个 createRequestHandler 函数,该函数接受一个参数对象。该对象包含一个 build 参数,必须设置为 npx expo export 创建的 dist/server 输出目录的相对路径。一些适配器可能还接受更多值来配置运行时 API。
🌐 By convention, all adapters export a createRequestHandler function that accepts a parameters object. This accepts a build parameter that must be set to the relative path to the dist/server output directory that npx expo export created. Some adapters may also accept more values to configure the runtime API.
import path from 'node:path'; import { createRequestHandler } from 'expo-server/adapter/http'; const onRequest = createRequestHandler({ build: path.join(process.cwd(), 'dist/server'), environment: process.env.NODE_ENV, });
应用接口
🌐 API
No API data file found, sorry!