'vuejs 401 unauthorized with axios from django backend with token
im trying to fetch data from django rest backend with axios in vuejs frontend but each time i get this error. the tokens match but it is still not authorizing.
{"message":"Request failed with status code 401","name":"AxiosError","config":{"transitional":{"silentJSONParsing":true,"forcedJSONParsing":true,"clarifyTimeoutError":false},"transformRequest":[null],"transformResponse":[null],"timeout":0,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1,"maxBodyLength":-1,"env":{"FormData":null},"headers":{"Accept":"application/json, text/plain, */*","Authorization":"Token838881311c52b89dd937815066e7eb3a3221604c"},"baseURL":"http://127.0.0.1:8000","method":"get","url":"/api/v1/clients/"},"code":"ERR_BAD_REQUEST","status":401}
the axios looks like this
axios
.get('/api/v1/clients/')
.then(response => {
for(let i = 0; i< response.data.length; i++){
this.clients.push(response.data[i])
}
})
.catch(error => {
console.log(JSON.stringify(error))
})
}
the settings in my django are
ALLOWED_HOSTS = ['*']
CORS_ALLOWED_ORIGINS = [
"http://localhost:8080",
"http://127.0.0.1:8000",
]
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES":(
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES':(
'rest_framework.permissions.IsAuthenticated',
)
}
Solution 1:[1]
When using TokenAuthentication
in Django Rest Framework, the Authorization
header should have as a value a string containing the keyword Token
followed by a blank space and after that the value of the token. In this case the corresponding header should look like:
"Authorization":"Token 838881311c52b89dd937815066e7eb3a3221604c"
The Token
keyword may be overriden if needed. To see some examples you can take a look at
https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | mtzd |