15

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,133
  • 6
  • 37
  • 60
  • 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

2 Answers2

5

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
  • 5,809
  • 1
  • 16
  • 32
5

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
  • 8,594
  • 3
  • 24
  • 45
  • How does this work? You need a templating engine to dynamically put variables defined by the server side. – Byrd Nov 08 '18 at 18:41
  • @Byrd yes, you can use any of your choice – GProst Nov 08 '18 at 19:17
  • thanks i just had my express serve a file it can use to inject the variable and make them available on the react app – Byrd Nov 08 '18 at 21:30
  • I'm using nginx as the web server. Is it possible for anyone to explain on how to set the headers with the request – Ismail Iqbal May 26 '22 at 15:27