主题
headers
headers 是一个异步函数,允许你从 服务器组件 读取 HTTP 传入请求标头。
¥headers is an async function that allows you to read the HTTP incoming request headers from a Server Component.
tsx
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 aniteratorallowing 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 thisHeadersobject.Headers.get():返回具有给定名称的Headers对象内标头的所有值的String序列。¥
Headers.get(): Returns aStringsequence of all the values of a header within aHeadersobject with a given name.Headers.has():返回一个布尔值,说明Headers对象是否包含某个标头。¥
Headers.has(): Returns a boolean stating whether aHeadersobject contains a certain header.Headers.keys():返回iterator,允许你浏览此对象中包含的键/值对的所有键。¥
Headers.keys(): Returns aniteratorallowing you to go through all keys of the key/value pairs contained in this object.Headers.values():返回iterator,允许你浏览该对象中包含的键/值对的所有值。¥
Headers.values(): Returns aniteratorallowing you to go through all values of the key/value pairs contained in this object.
很高兴知道
¥Good to know
headers是一个返回 promise 的异步函数。你必须使用async/await或 React 的use函数。¥
headersis an asynchronous function that returns a promise. You must useasync/awaitor React'susefunction.在版本 14 及更早版本中,
headers是一个同步函数。为了帮助向后兼容,你仍然可以在 Next.js 15 中同步访问它,但此行为将来会被弃用。¥In version 14 and earlier,
headerswas a synchronous function. To help with backwards compatibility, you can still access it synchronously in Next.js 15, but this behavior will be deprecated in the future.
由于
headers是只读的,因此你无法set或delete传出的请求标头。¥Since
headersis read-only, you cannotsetordeletethe outgoing request headers.headers是一个 动态 API,其返回值无法提前得知。在中使用它将会选择进入 动态渲染 的路由。¥
headersis 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
版本历史
¥Version History
| 版本 | 更改 |
|---|---|
v15.0.0-RC | headers 现在是一个异步函数。codemod 可用。 |
v13.0.0 | headers 已引入。 |