# gt-node: General Translation Node.js SDK: getRequestLocale
URL: https://generaltranslation.com/zh/docs/node/reference/functions/get-request-locale.mdx
Docs index: https://generaltranslation.com/llms.txt
Description: 使用 General Translation 从请求的 Accept-Language 标头中检测最合适的受支持区域设置。getRequestLocale 的 API 参考。

从请求的 `Accept-Language` 标头中提取首选区域设置，并与你已配置的区域设置进行匹配。可用它来选择要与 [`withGT`](/docs/node/reference/functions/with-gt) 绑定的区域设置。

## 概览 [#overview]

使用请求对象调用 `getRequestLocale`。它会返回最匹配的受支持区域设置；如果找不到匹配项，则返回 `defaultLocale`。

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

const locale = getRequestLocale(req); // 'fr'
```

签名：

```ts
getRequestLocale(request: { headers: Record<string, string | string[] | undefined> }): string
```

*注意：请先调用 [`initializeGT`](/docs/node/reference/functions/initialize-gt)，再使用 `getRequestLocale`，这样它才能识别支持哪些区域设置。*

## 工作方式 [#how-it-works]

* **Header 解析。** 它会解析请求中的 `Accept-Language` 标头，并在你配置的 `locales` 中协商出最佳匹配项。
* **后备。** 当没有匹配的受支持区域设置时，它会返回已配置的 `defaultLocale`。
* **与框架无关。** 它适用于任何将 headers 暴露为 `Record<string, string | string[] | undefined>` 的框架，包括 Express 和 Fastify。

## 参数 [#parameters]

| 参数                    | 描述                              | 类型                                                             | 可选 | 默认值 |
| --------------------- | ------------------------------- | -------------------------------------------------------------- | -- | --- |
| [`request`](#request) | 一个包含 `headers` 属性的对象，该属性中包含请求头。 | `{ headers: Record<string, string \| string[] \| undefined> }` | 否  | —   |

### `request` [#request]

**Type** `{ headers: Record<string, string | string[] | undefined> }` · **必填**

一个包含 `headers` 属性的对象，该属性中包含请求头。适用于 Express、Fastify，以及任何将请求头暴露为 `Record<string, string | string[] | undefined>` 的框架。

## 返回值 [#returns]

**类型** `string`

从已配置的 locales 中选出的最佳匹配 BCP 47 区域设置代码；如果未找到匹配项，则返回 `defaultLocale`。

## 示例 [#examples]

```ts title="middleware/locale.js"
// Express 中间件
import { withGT, getRequestLocale } from 'gt-node';

export function localeMiddleware(req, res, next) {
  const locale = getRequestLocale(req);
  withGT(locale, () => next());
}
```

```ts title="middleware/locale.js"
// 与其他策略结合使用 — 将 getRequestLocale 作为后备
import { withGT, getRequestLocale } from 'gt-node';

export function localeMiddleware(req, res, next) {
  const locale =
    req.query.lang ||
    req.cookies?.locale ||
    getRequestLocale(req);

  withGT(locale, () => next());
}
```

## Sitemap

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