I have an endpoint that I made using djangorestframework. The view has a dispatch method for retrieving data from the request and sending it to post method. Endpoint:
class Profile(APIView):
permission_classes = [IsAuthenticated]
data = None
def dispatch(self, request, *args, **kwargs):
if request.content_type == 'application/json':
try:
self.data = json.loads(request.body)
except json.JSONDecodeError:
return super().dispatch(request, *args, **kwargs)
else:
return super().dispatch(request, *args, **kwargs)
I tested this endpoint with 'Authorization': 'Bearer ${token}'
header using postman and rest file, and I am getting the data back with status 200. But when I do the same thing in React using axios.post method, the same user is unauthorized.
Axios.post:
useEffect(() => {
axios.post('http://127.0.0.1:8000/user/profile/', {
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${token}`
},
body: {
"username": "Caution1",
"password": "Caution123"
}
}).then(response => {setData(response.data); console.log(data);});
}, []);
I have CORS_ALLOW_ALL_ORIGINS
and CORS_ALLOW_CREDENTIALS
both to True.
I have an endpoint that I made using djangorestframework. The view has a dispatch method for retrieving data from the request and sending it to post method. Endpoint:
class Profile(APIView):
permission_classes = [IsAuthenticated]
data = None
def dispatch(self, request, *args, **kwargs):
if request.content_type == 'application/json':
try:
self.data = json.loads(request.body)
except json.JSONDecodeError:
return super().dispatch(request, *args, **kwargs)
else:
return super().dispatch(request, *args, **kwargs)
I tested this endpoint with 'Authorization': 'Bearer ${token}'
header using postman and rest file, and I am getting the data back with status 200. But when I do the same thing in React using axios.post method, the same user is unauthorized.
Axios.post:
useEffect(() => {
axios.post('http://127.0.0.1:8000/user/profile/', {
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${token}`
},
body: {
"username": "Caution1",
"password": "Caution123"
}
}).then(response => {setData(response.data); console.log(data);});
}, []);
I have CORS_ALLOW_ALL_ORIGINS
and CORS_ALLOW_CREDENTIALS
both to True.
- Can you inspect network in your browser and check the response? It can provides userful informations: are the headers correctly set, response code, browser error (e.g. CORS) etc... – Jean Bouvattier Commented Feb 10 at 9:28
1 Answer
Reset to default 0rewrite your request in axios
useEffect(() => {
axios.post('http://127.0.0.1:8000/user/profile/', {
"username": "Caution1",
"password": "Caution123"
},{
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${token}`
},
}).then(response => {setData(response.data); console.log(data);});
}, []);