How do I get http headers in React.js

旧时模样 提交于 2020-01-01 09:16:30

问题


I've made a request to a React page, and I need to get the headers from the request.

I call the page via the URL:

http://localhost/dashboard

and I set headers, for example 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?


回答1:


You cant get current page headers without sending a http request via javascript. See this answer for more info.

Add a dummy api url on your server and hit it after your page loadn then you can get the headers.

class App extends React.Component{
    //some code
    componentDidMount(){
       fetch(Some_API).then(response=>{
           console.log(response.headers)
       })
    }
    //some code
}



回答2:


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.html of your React app. For example:

//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.



来源:https://stackoverflow.com/questions/44354763/how-do-i-get-http-headers-in-react-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!