NextRequest
NextRequest 扩展了 Web Request API,并提供了额外的便捷方法。
cookies
读取或修改请求的 Set-Cookie 头部。
set(name, value)
给定一个名称,在请求上设置一个带有给定值的 Cookie。
// Given incoming request /home
// Set a cookie to hide the banner
// request will have a `Set-Cookie:show-banner=false;path=/home` header
request.cookies.set('show-banner', 'false')get(name)
给定一个 cookie 名称,返回该 cookie 的值。如果未找到 cookie,则返回 undefined。如果找到多个 cookie,则返回第一个。
// Given incoming request /home
// { name: 'show-banner', value: 'false', Path: '/home' }
request.cookies.get('show-banner')getAll()
给定一个 Cookie 名称,返回该 Cookie 的值。如果没有给定名称,则返回请求上的所有 Cookie。
// Given incoming request /home
// [
// { name: 'experiments', value: 'new-pricing-page', Path: '/home' },
// { name: 'experiments', value: 'winter-launch', Path: '/home' },
// ]
request.cookies.getAll('experiments')
// Alternatively, get all cookies for the request
request.cookies.getAll()delete(name)
给定一个 Cookie 名称,从请求中删除该 Cookie。
// Returns true for deleted, false is nothing is deleted
request.cookies.delete('experiments')has(name)
给定一个 Cookie 名称,如果该 Cookie 存在于请求中,则返回 true。
// Returns true if cookie exists, false if it does not
request.cookies.has('experiments')clear()
从请求中移除 Set-Cookie 头部。
request.cookies.clear()nextUrl
扩展了原生的 URL API,提供了额外的便捷方法,包括 Next.js 特定的属性。
// Given a request to /home, pathname is /home
request.nextUrl.pathname
// Given a request to /home?name=lee, searchParams is { '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 对象。 |
版本历史
| 版本 | 更改 |
|---|---|
v15.0.0 | ip 和 geo 已移除。 |
这有帮助吗?