myrrtle
myrrtle

Reputation: 55

How to pass Authorization token in a React application

I'm working on the react part of a web app with NodeJs as backend. I'm having issue with passing authorization after login action. When a user logs in, a token is generated and I take this token and save it in the local storage. Then I use it to control users on the website with the below code:

    const PrivateRoute = ({component: Component, ...rest}) =>(
      <Route {...rest} render={(props) => (
        window.localStorage.token !== undefined
         ? <Component {...props} />
         : <Redirect to="/" />
    )} />

Now this works well, but when I try to make a post request to the server, I get the below error:

  { type: "ValidationError", details: "Authorization token not passed"}
   details: "Authorization token not passed" type:"ValidationError"

I have done some googling and I think the error occurs because I didn't set the header object for the application. I may be wrong though.

Please i'll appreciate any assistance on how I can resolve this issue. Thanks

Upvotes: 2

Views: 2386

Answers (1)

Meir
Meir

Reputation: 14375

axios, same as fetch, can accept a second parameter with config, part of which can be the auth token, so, you can pass in something like this:

axios.get(url, {
  headers: {
    authorization: `Bearer ${auth_token}`
    other_header1: 'value',
    other_header2: 'value2'
  }
}

Alternatively, upon getting your token, you can set it as a default value, look for 'config defaults' in axios docs.

Upvotes: 2

Related Questions