17

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?

Wayneio
  • 3,466
  • 7
  • 42
  • 73
  • What headers? There is no `http-request` going on. With react-router you just decide what component to show on which `route`. But there is no http-request. Correct me if I'm wrong. – Anurag Awasthi Jun 04 '17 at 14:26
  • @anuragasaurus I see what you mean, when navigating via other pages. I'm talking in terms of the first request from another URL to this one, passing in headers. I've updated the question. – Wayneio Jun 04 '17 at 14:43

3 Answers3

7

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.

GProst
  • 9,229
  • 3
  • 25
  • 47
4

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
}
Anurag Awasthi
  • 6,115
  • 2
  • 18
  • 32
0

I had to solve this same issue, NOT the same request, hence won't work for diff users trying to get in (auth) at the same time.

Using Server Side scripting to mod your html OR put it "somewhere client can access" is probably the way to go. i.e. session var or some db lookup key in the initial server req with the auth info, then have client use the same key to fetch the auth. (this may open up to session hijacks... so I'm still pondering for a better solution.

  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 07 '23 at 22:32