node.js 我如何在 React.js 中获取 http 标头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44354763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get http headers in React.js
提问by Wayneio
I've made a request to a React page, and I need to get the headers from the request.
我已向 React 页面发出请求,我需要从请求中获取标头。
I call the page via the URL:
我通过 URL 调用页面:
and I set headers, for example authcode=1234.
我设置了标题,例如 authcode=1234。
I then load the page with this route:
然后我用这条路线加载页面:
<Route path="dashboard" name="dashboard" component={Dashboard} onEnter={requireAuth}></Route>
is there something like this.props.header, I can call in the page constructor?
有没有像this.props.header这样的东西,我可以在页面构造函数中调用?
采纳答案by Anurag Awasthi
You cant get current page headers without sending a http request via javascript. See this answer for more info.
如果不通过 javascript 发送 http 请求,您将无法获取当前页面标题。有关更多信息,请参阅此答案。
Add a dummy api url on your server and hit it after your page loadn then you can get the headers.
在您的服务器上添加一个虚拟 api url,并在您的页面加载后点击它,然后您就可以获得标题。
class App extends React.Component{
//some code
componentDidMount(){
fetch(Some_API).then(response=>{
console.log(response.headers)
})
}
//some code
}
回答by GProst
It's not possible to access page headers via client JavaScript. You can get these request headers on your server side and then pass them into index.htmlof your React app. For example:
无法通过客户端 JavaScript 访问页眉。您可以在服务器端获取这些请求标头,然后将它们传递到index.html您的 React 应用程序中。例如:
//in index.html
<head>
...
<script>
window.__INITIAL_HEADERS__ = {/* page headers */};
</script>
</head>
<body>
...
</body>
Then in your app you can access the headers via window.__INITIAL_HEADERS__variable.
然后在您的应用程序中,您可以通过window.__INITIAL_HEADERS__变量访问标头。

