Django + React: Can't get access to an endpoint
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 think the issue is how your Axios request is structured. The headers and data should be passed separately, and Axios does not use body as a parameter. So instead, your payload will be sent as second argument and header as third.
Here's what it should look like:
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(response.data);
}).catch(error => {
console.error("Error:", error.response);
});
}, []);
Still the error persists then try defining this explicitly:
CORS_ALLOW_HEADERS = ['content-type', 'authorization']
Because some browsers block credentialed requests (Authorization
headers) unless you explicitly set it.