# gt-node: General Translation Node.js SDK: 确定请求的区域设置
URL: https://generaltranslation.com/zh/docs/node/guides/detecting-locale.mdx
Docs index: https://generaltranslation.com/llms.txt
Description: 介绍如何在 gt-node 中使用 General Translation 为每个请求解析并绑定区域设置。

在 `gt-node` 中，每次翻译调用都会使用当前请求的区域设置。你需要从请求中解析出该区域设置，并通过 [`withGT`](/docs/node/reference/functions/with-gt) 将其绑定，这样下游的所有翻译函数都会使用它。

## 使用 `withGT` 绑定区域设置 [#with-gt]

用 `withGT(locale, fn)` 包装请求处理逻辑。它会在整个请求期间保存该区域设置，使 [`getGT`](/docs/node/reference/functions/get-gt)、[`getMessages`](/docs/node/reference/functions/get-messages)、[`tx`](/docs/node/reference/functions/tx) 和 [`getLocale`](/docs/node/reference/functions/get-locale) 都基于该区域设置进行解析。

```ts
import { withGT } from 'gt-node';

app.use((req, res, next) => withGT(resolveLocale(req), () => next()));
```

*注意：在 [`withGT`](/docs/node/reference/functions/with-gt) 作用域之外调用翻译函数或区域设置函数，在开发环境中会抛出错误；在生产环境中则会回退到默认区域设置。*

## 从 `Accept-Language` 检测 [#accept-language]

使用 [`getRequestLocale`](/docs/node/reference/functions/get-request-locale) 从请求的 `Accept-Language` 标头中选择最合适的受支持区域设置；如果无法确定，则回退到默认区域设置。

```ts
import { withGT, getRequestLocale } from 'gt-node';

app.use((req, res, next) => withGT(getRequestLocale(req), () => next()));
```

## 根据你自己的信号进行检测 [#custom]

为了遵循用户的明确选择，请自行解析区域设置——例如从 cookie 或路径片段中获取——并在无法确定时回退到 [`getRequestLocale`](/docs/node/reference/functions/get-request-locale)。将结果传给 [`withGT`](/docs/node/reference/functions/with-gt)。

```ts
function resolveLocale(req) {
  return req.cookies?.locale || getRequestLocale(req);
}

app.use((req, res, next) => withGT(resolveLocale(req), () => next()));
```

[`withGT`](/docs/node/reference/functions/with-gt) 会根据你配置的 `locales` 解析传入的值，因此如果某个区域设置不受支持，就会回退到默认值。你可以在一次请求中的任何位置使用 [`getLocale`](/docs/node/reference/functions/get-locale) 读取当前生效的区域设置。

## Next steps

- /docs/node/guides/translating-strings
- /docs/node/guides/configuring
- /docs/node/guides/storing-translations

## Sitemap

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