NextRequest
NextRequest 扩展了 Web Request API,提供额外的便利方法。
cookies
读取或修改请求的 Set-Cookie
头。
set(name, value)
给定一个名称,在请求上设置具有给定值的 cookie。
// 给定传入请求 /home
// 设置一个 cookie 来隐藏横幅
// 请求将有一个 `Set-Cookie:show-banner=false;path=/home` 头
request.cookies.set('show-banner', 'false')
get(name)
给定一个 cookie 名称,返回 cookie 的值。如果找不到 cookie,则返回 undefined
。如果找到多个 cookie,则返回第一个。
// 给定传入请求 /home
// { name: 'show-banner', value: 'false', Path: '/home' }
request.cookies.get('show-banner')
getAll()
给定一个 cookie 名称,返回 cookie 的值。如果没有给出名称,则返回请求上的所有 cookie。
// 给定传入请求 /home
// [
// { name: 'experiments', value: 'new-pricing-page', Path: '/home' },
// { name: 'experiments', value: 'winter-launch', Path: '/home' },
// ]
request.cookies.getAll('experiments')
// 或者,获取请求的所有 cookie
request.cookies.getAll()
delete(name)
给定一个 cookie 名称,从请求中删除 cookie。
// 删除时返回 true,如果没有删除任何内容则返回 false
request.cookies.delete('experiments')
has(name)
给定一个 cookie 名称,如果请求上存在 cookie 则返回 true
。
// 如果 cookie 存在则返回 true,否则返回 false
request.cookies.has('experiments')
clear()
从请求中 移除 Set-Cookie
头。
request.cookies.clear()
nextUrl
扩展原生 URL
API,提供额外的便利方法,包括 Next.js 特定属性。
// 给定对 /home 的请求,pathname 是 /home
request.nextUrl.pathname
// 给定对 /home?name=lee 的请求,searchParams 是 { 'name': 'lee' }
request.nextUrl.searchParams
以下选项可用:
属性 | 类型 | 描述 |
---|---|---|
basePath | string | URL 的 基础路径。 |
buildId | string | undefined | Next.js 应用程序的构建标识符。可以 自定义。 |
defaultLocale | string | undefined | 国际化 的默认语言环境。 |
domainLocale | ||
- defaultLocale | string | 域内的默认语言环境。 |
- domain | string | 与特定语言环境关联的域。 |
- http | boolean | undefined | 指示域是否使用 HTTP。 |
locales | string[] | undefined | 可用语言环境的数组。 |
locale | string | undefined | 当前活动的语言环境 。 |
url | URL | URL 对象。 |
属性 | 类型 | 描述 |
---|---|---|
basePath | string | URL 的 基础路径。 |
buildId | string | undefined | Next.js 应用程序的构建标识符。可以 自定义。 |
pathname | string | URL 的路径名。 |
searchParams | Object | URL 的搜索参数。 |
注意: Pages 路由器的国际化属性在 App 路由器中不可用。了解更多关于 App 路由器的国际化。
版本历史
版本 | 更改 |
---|---|
v15.0.0 | 移除了 ip 和 geo 。 |