NNext.js 中文网 GitHub

NextRequest

NextRequest 的 API 参考

NextRequest 通过额外的便捷方法扩展了 Web Request API。

cookies#

读取或修改请求的 Set-Cookie 头。

set(name, value)#

给定名称,在请求上设置具有给定值的 cookie。

ts
// 给定传入请求 /home
// 设置一个 cookie 以隐藏横幅
// 请求将具有 `Set-Cookie:show-banner=false;path=/home` 头
request.cookies.set('show-banner', 'false')

get(name)#

给定 cookie 名称,返回该 cookie 的值。如果未找到 cookie,则返回 undefined。如果找到多个 cookie,则返回第一个。

ts
// 给定传入请求 /home
// { name: 'show-banner', value: 'false', Path: '/home' }
request.cookies.get('show-banner')

getAll()#

给定 cookie 名称,返回该 cookie 的值。如果未给定名称,则返回请求中的所有 cookie。

ts
// 给定传入请求 /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。

ts
// 删除成功返回 true,未删除任何内容则返回 false
request.cookies.delete('experiments')

has(name)#

给定 cookie 名称,如果请求中存在该 cookie,则返回 true。

ts
// 如果 cookie 存在则返回 true,否则返回 false
request.cookies.has('experiments')

clear()#

从请求中删除所有 cookie。

ts
request.cookies.clear()

nextUrl#

使用额外的便捷方法扩展原生 URL API,包括 Next.js 特定的属性。

ts
// 给定对 /home 的请求,pathname 为 /home
request.nextUrl.pathname
// 给定对 /home?name=lee 的请求,searchParams 为 { 'name': 'lee' }
request.nextUrl.searchParams

以下选项可用:

属性类型描述
basePathstringURL 的基本路径。
buildIdstring \undefined
defaultLocalestring \undefined
domainLocale
- defaultLocalestring某个域名内的默认区域设置。
- domainstring与特定区域设置关联的域名。
- httpboolean \undefined
localesstring[] \undefined
localestring \undefined
urlURLURL 对象。
属性类型描述
basePathstringURL 的基本路径。
buildIdstring \undefined
pathnamestringURL 的路径名。
searchParamsObjectURL 的搜索参数。

注意: Pages Router 的国际化属性无法在 App Router 中使用。了解更多关于App Router 中的国际化的信息。

版本历史#

版本变更
v15.0.0移除了 ip 和 geo。
Next.js 中文网