英文:
How to access request information inside the app directory, like with getServerSideProps context parameter?
问题
我想能够查看来自我的组件的请求数据。我尝试过查阅文档,但没有找到任何信息。
如果我不能这样做,是否有其他方法可以实现?
为了了解背景情况,我正在尝试检查请求的主体是否包含令牌,并检查是否正确,然后将其重定向到正确的网站。
英文:
Basically, I want to be able to see the request data from my component. I've tried searching through the docs but haven't found anything.
If I can't do that, is there any other way I can do so?
And for context, I am trying to check if the request has the token in its body and checking if it is right and redirecting it to the right site
答案1
得分: 0
在app
目录中,您可以使用headers()
和cookies()
函数来访问请求头和Cookie。在从pages
迁移到app
文件夹的指南中,他们提到了以下内容:
> app
目录公开了新的只读函数,用于检索请求数据:
>
> headers()
:基于Web Headers API,可在Server Components内部用于检索请求头。
>
> cookies()
:基于Web Cookies API,可在Server Components内部用于检索Cookie。
// app/page.js
import { cookies, headers } from 'next/headers'
async function getData() {
const authHeader = headers().get('authorization')
return '...'
}
export default async function Page() {
// 您可以在Server Components内部直接使用`cookies()`或`headers()`,或在数据获取函数中使用它们
const theme = cookies().get('theme')
const data = await getData()
return '...'
}
英文:
In the app
dir, you can acces request headers and cookies with headers()
, and cookies()
functions. On the migration from the pages
to the app
folder guide, they say the following:
>The app
directory exposes new read-only functions to retrieve request data:
>
>headers()
: Based on the Web Headers API, and can be used inside Server Components to retrieve request headers.
>
>cookies()
: Based on the Web Cookies API, and can be used inside Server Components to retrieve cookies.
// app/page.js
import { cookies, headers } from 'next/headers'
async function getData() {
const authHeader = headers().get('authorization')
return '...'
}
export default async function Page() {
// You can use `cookies()` or `headers()` inside Server Components
// directly or in your data fetching function
const theme = cookies().get('theme')
const data = await getData()
return '...'
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论