# node: getRequestLocale
URL: https://generaltranslation.com/zh/docs/node/api/get-request-locale.mdx
---
title: getRequestLocale
description: getRequestLocale 函数的 API 参考
---
## 概述
`getRequestLocale` 函数会从请求的 `Accept-Language` 标头中提取首选区域设置,并将其与已配置的区域设置进行匹配。
```js
import { getRequestLocale } from 'gt-node';
const locale = getRequestLocale(req); // 'fr'(法语区域设置)
```
**需要先初始化:**
使用 `getRequestLocale` 之前,请先调用 [`initializeGT`](/docs/node/api/initialize-gt),以便其知晓支持哪些区域设置。
## 参考文档
### 参数
的框架。',
optional: false,
},
}}
/>
### 返回值
`string` — 在你已配置的区域设置中,最符合的 BCP 47 [区域设置代码](/docs/core/locales);如果未找到匹配项,则返回 `defaultLocale`。
***
## 示例
### Express 中间件
```js title="middleware/locale.js"
import { withGT, getRequestLocale } from 'gt-node';
export function localeMiddleware(req, res, next) {
const locale = getRequestLocale(req);
withGT(locale, () => next());
}
```
### 结合其他策略使用
未设置明确偏好时,可使用 `getRequestLocale` 作为回退内容:
```js title="middleware/locale.js"
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());
}
```
***
## 下一步
* 请参阅 [`getLocale`](/docs/node/api/get-locale),了解如何在 `withGT` 上下文中读取区域设置。
* 请参阅 [区域设置检测与中间件](/docs/node/guides/middleware) 指南,了解完整的中间件模式。