【问题标题】:How do you get "x-" headers in Next.js如何在 Next.js 中获取“x-”标头
【发布时间】:2020-11-02 00:39:08
【问题描述】:

我正在关注 Sara Vieira 的 Opinionated Guide to React 中的示例。在示例中,她正在执行以下操作:

export async function getServerSideProps({ req }) {
  const ip = req.headers['x-real-ip']
  console.log(req.headers)
  const { data } = await axios(`http://ip-api.com/json/${ip}`)

  return {
    props: {
      location: data,
    },
  }
}

我的标头控制台日志是:

{
  host: 'localhost:3000',
  connection: 'keep-alive',
  'cache-control': 'max-age=0',
  'upgrade-insecure-requests': '1',
  'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) 
  Chrome/86.0.4240.111 Safari/537.36',
  accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
  'sec-fetch-site': 'same-origin',
  'sec-fetch-mode': 'navigate',
  'sec-fetch-dest': 'document',
  referer: 'http://localhost:3000/',
  'accept-encoding': 'gzip, deflate, br',
  'accept-language': 'en-US,en;q=0.9,fr;q=0.8,ru;q=0.7,it;q=0.6'

}

x- 标头均未通过。我想这是因为我正在运行dev

根据https://github.com/vercel/next.js/issues/7377,由于SSR,x- 标头只能在_app.js_document.js 中访问。

你能帮忙吗!

【问题讨论】:

  • 能不能尝试在本地使用 curl -i -H "x-forward-for: 1.1.1.1" localhost:3000 看看能不能看到x- header?

标签: node.js reactjs http-headers next.js


【解决方案1】:

NextJS 内置在中间件 API 路由中不提供 req.headers。相反,您需要根据您的请求传递 cookie。

const { ip } = req.cookies

如果你有带有值的 ip name cookie,你可以在 req.cookies 上解构它

这里是文档https://nextjs.org/docs/api-routes/api-middlewares

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-18
    • 1970-01-01
    • 1970-01-01
    • 2014-12-20
    • 2020-10-08
    • 2017-11-05
    相关资源
    最近更新 更多