DEV Community

Muhamad Rahmat Setiawan
Muhamad Rahmat Setiawan

Posted on

how to insert app-token into the header on axios and react js?

first I post the API to the "api / app-token" endpoint "The API doesn't need a header", after that the response from the "api / app-token" is stored in the localstorage with the app-token key, after saving it in the localstorage I take app- I then set the token to the header to post another API endpoint that requires a header, the problem is that the header cannot retrieve data from localstorage so the other endpoint cannot be accessed because the header has not been filled with app-tokens that are in localstorage, I try to outsmart it with force the app-token to a state when the stat is loaded then I make the page refresh "window.location.reload ()", but why isn't the function running? or is there a more efficient way?

There are basically 2 endpoints, the first endpoint "api / app-token" does not need a header, then the second endpoint requires a header, and the header must be filled with app-tokens that I set into localstorage

this is example axios post for get app-token

const [getAppToken, setgetAppToken] = useState({})
  const [company, setCompany] = useState({
    company_name: 'fevci',
    comp_key: 'fevci123'
  })

  useEffect(() => {
    const getAppToken = async () => {
      const res = await axios({
        method: 'post',
        url: endpoint + 'api/app_token',
        data: company,
      })
      const { data: appToken, success } = res.data

      if (success === true) {
        storage.setItem('app-token', JSON.stringify(appToken))
      } else {
        storage.removeItem('app-token')
      }

      return res
    }
    getAppToken()
  }, [])
Enter fullscreen mode Exit fullscreen mode

and this is an example of axios which has a header assuming the header has been filled with app-tokens

export const api = axios.create({
  baseURL: endpoint,
  headers: {
    'app-token': (storage.getItem('app-token') !== null) ? JSON.parse(storage.getItem('app-token')) : null,
    'Authorization': (storage.getItem('token') !== null) ? JSON.parse(storage.getItem('token')) : null,
    'content-type': 'multipart/form-data'
  }
})
Enter fullscreen mode Exit fullscreen mode

Top comments (0)