如何在 Next.js 中获取“x-”标头

Tit*_*hos 12 http-headers node.js reactjs next.js

我正在遵循 Sara Vieira 的 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,
    },
  }
}
Run Code Online (Sandbox Code Playgroud)

我的标题控制台日志是:

{
  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'
Run Code Online (Sandbox Code Playgroud)

}

没有任何x-标头通过。我想这是因为我在跑步dev

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

你能帮我吗!

小智 0

你可以尝试这样的方法:

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
    }
  };
}
Run Code Online (Sandbox Code Playgroud)