Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

291
Views
How to use token authorization with axios in react.js

I have this function in react.js that should access a django rest framework using a token access:

 getAll(token) {
        axios.defaults.headers.common['Authorization'] = "Token " + token
        return axios.get('http://localhost:8000/api/todos/');

I keep getting:

GET http://localhost:8000/api/todos/ 401 (Unauthorized)

I have tried calling the http request on Insomnia and everything seems fine. the successful curl request from Insomnia is

curl --request GET \
  --url http://127.0.0.1:8000/api/todos \
  --header 'Authorization: Token 9a60ef4a5fbaab1b0fa9c3e8e8a5626b757e148d' \
  --header 'Content-Type: application/json' \
  --cookie csrftoken=MtpItNeHebjs7OaAfTTJBO3x4ezh5FfnVg1mNjOuNTy1piK9DXxSusb4oxW2qy1e

How would I implement this token request using axios in react.js

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

I think the issue might be

"Token " + token

I think the rest API is looking for a bearer token as authorization so you might want to use

 axios.defaults.headers.common['Authorization'] = "Bearer " + token
about 4 years ago · Juan Pablo Isaza Report

0

Yes, Mandip Giri's answer would work.

Though for convenience sake I would suggest creating file src/utility/axiosInstance.js or something equivalent with contents like this:

import axios from 'axios';

export const axiosInstance = axios.create({
  baseURL: 'https://example.com',
});

export const setToken = (token) => {
  const auth = `Bearer ${token}`;
  axiosInstance.defaults.headers.common['Authorization'] = auth;
};

Than you import axiosInstance and setToken method into whatever component you need and use accordingly to the requirements.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!