NodeJS 如何在Next.js中获取“x-”头文件

thigvfpy  于 2023-10-17  发布在  Node.js
关注(0)|答案(1)|浏览(117)

这是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中访问。
你能帮忙吗!

h9vpoimq

h9vpoimq1#

你可以试试这样:

export async function getServerSideProps(context) {
  const { req } = context;
  
  // Access custom "x-" headers using the req object
  const customHeader = req.headers['x-custom-header'];
  
  // Now, you can use the customHeader value in your logic
  // ...

  return {
    props: {
      // Your data to pass to the component
    }
  };
}

相关问题