# node: withGT URL: https://generaltranslation.com/zh/docs/node/api/with-gt.mdx --- title: withGT description: withGT 请求包装器的 API 参考文档 --- ## 概述 `withGT` 函数会包装一个回调函数,为翻译函数提供区域设置上下文。 在 Node.js 服务器中,每个请求通常对应不同的用户,并且这些用户可能使用不同的区域设置。 `withGT` 会为回调中调用的所有翻译函数设置区域设置。 ```js import { withGT } from 'gt-node'; app.get('/api/greeting', (req, res) => { withGT(req.locale, () => { // 此处的翻译函数使用 req.locale }); }); ``` **请求上下文:** `withGT` 底层使用异步本地存储,将区域设置限定在当前请求范围内。 回调中对 `getGT` 和 `getMessages` 的所有调用都会使用提供的区域设置。 ## 参考 ### 参数 T', optional: false, }, }} /> ### 说明 | 参数 | 说明 | | -------- | -------------------------------------------------------------- | | `locale` | 在该回调中用于翻译的[区域设置代码](/docs/core/locales) (例如 `'es'`、`'fr-CA'`) 。 | | `fn` | 在给定的区域设置上下文中执行的回调函数。可以是同步或异步函数。 | ### 返回值 `T` — 回调函数 `fn` 返回的值。 *** ## 示例 ### Express 中间件 ```js title="server.js" import express from 'express'; import { initializeGT, withGT, getGT } from 'gt-node'; initializeGT({ defaultLocale: 'en-US', locales: ['en-US', 'es', 'fr'], projectId: process.env.GT_PROJECT_ID, }); const app = express(); app.use((req, res, next) => { const locale = req.headers['accept-language']?.split(',')[0] || 'en-US'; withGT(locale, () => { next(); }); }); app.get('/api/greeting', async (req, res) => { const gt = await getGT(); res.json({ message: gt('Hello, world!') }); }); ``` ### 封装异步处理函数 ```js title="handler.js" import { withGT, getGT } from 'gt-node'; export async function handleRequest(locale: string) { return withGT(locale, async () => { const gt = await getGT(); return gt('Welcome to our app!'); }); } ``` *** ## 注意事项 * 必须先调用 `initializeGT`,然后才能使用 `withGT`。否则会抛出错误。 * 区域设置上下文仅在该回调内生效,不会泄漏到其他并发请求。 * `withGT` 同时支持同步和异步回调。 ## 后续步骤 * 初始设置请参阅 [`initializeGT`](/docs/node/api/initialize-gt)。 * 如需在请求上下文中翻译字符串,请参阅 [`getGT`](/docs/node/api/get-gt)。