How to access request information inside the app directory, like with getServerSideProps context parameter?

huangapple go评论86阅读模式
英文:

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 '...'
}

huangapple
  • 本文由 发表于 2023年6月18日 18:36:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76500103.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定