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
CodePudding user response:
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
CodePudding user response:
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.