headers
headers
是一个异步函数,允许你从 服务器组件 读取 HTTP 传入请求标头。
¥headers
is an async function that allows you to read the HTTP incoming request headers from a Server Component.
import { headers } from 'next/headers'
export default async function Page() {
const headersList = await headers()
const userAgent = headersList.get('user-agent')
}
import { headers } from 'next/headers'
export default async function Page() {
const headersList = await headers()
const userAgent = headersList.get('user-agent')
}
参考
¥Reference
参数
¥Parameters
headers
不带任何参数。
¥headers
does not take any parameters.
返回
¥Returns
headers
返回只读 网页标题 对象。
¥headers
returns a read-only Web Headers object.
-
Headers.entries()
:返回iterator
,允许遍历该对象中包含的所有键/值对。¥
Headers.entries()
: Returns aniterator
allowing to go through all key/value pairs contained in this object. -
Headers.forEach()
:对此Headers
对象中的每个键/值对执行一次提供的函数。¥
Headers.forEach()
: Executes a provided function once for each key/value pair in thisHeaders
object. -
Headers.get()
:返回具有给定名称的Headers
对象内标头的所有值的String
序列。¥
Headers.get()
: Returns aString
sequence of all the values of a header within aHeaders
object with a given name. -
Headers.has()
:返回一个布尔值,说明Headers
对象是否包含某个标头。¥
Headers.has()
: Returns a boolean stating whether aHeaders
object contains a certain header. -
Headers.keys()
:返回iterator
,允许你浏览此对象中包含的键/值对的所有键。¥
Headers.keys()
: Returns aniterator
allowing you to go through all keys of the key/value pairs contained in this object. -
Headers.values()
:返回iterator
,允许你浏览该对象中包含的键/值对的所有值。¥
Headers.values()
: Returns aniterator
allowing you to go through all values of the key/value pairs contained in this object.
很高兴知道
¥Good to know
-
headers
是一个返回 promise 的异步函数。你必须使用async/await
或 React 的use
函数。¥
headers
is an asynchronous function that returns a promise. You must useasync/await
or React'suse
function.-
在版本 14 及更早版本中,
headers
是一个同步函数。为了帮助实现向后兼容,你仍然可以在 Next.js 15 中同步访问它,但此行为将来会被弃用。¥In version 14 and earlier,
headers
was a synchronous function. To help with backwards compatability, you can still access it synchronously in Next.js 15, but this behavior will be deprecated in the future.
-
-
由于
headers
是只读的,因此你无法set
或delete
传出的请求标头。¥Since
headers
is read-only, you cannotset
ordelete
the outgoing request headers. -
headers
是一个 动态 API,其返回值无法提前得知。在中使用它将会选择进入 动态渲染 的路由。¥
headers
is a Dynamic API whose returned values cannot be known ahead of time. Using it in will opt a route into dynamic rendering.
示例
¥Examples
使用授权标头
¥Using the Authorization header
import { headers } from 'next/headers'
export default async function Page() {
const authorization = (await headers()).get('authorization')
const res = await fetch('...', {
headers: { authorization }, // Forward the authorization header
})
const user = await res.json()
return <h1>{user.name}</h1>
}
版本历史
¥Version History
版本 | 变化 |
---|---|
v15.0.0-RC | headers 现在是一个异步函数。codemod 可用。 |
v13.0.0 | headers 推出。 |