How to read headers from axios post in django?
I am sending an axios post to my django backend app:
async function sendBookingRequest() {
// console.log(date,bookedHours,cancha,cellphone)
try {
axios.post("https://danilo2588.pythonanywhere.com/book", {
headers: {'Authorization':"1234567890123456789012345678901234567890"},
params:{
'requested_date':date,
'hours':bookedHours,
'business':cancha,
'phone':cellphone,
}
})
.then( function(response){
setConfirmation(response.data)
setStepper(7)
})
.finally(
setIsLoading(false)
)
} catch(error){
console.log(error)
}; }
In my views I have:
def booking(request):
auth_key = request.headers.get('Authorization')
if auth_key:
generic_user = Token.objects.get(key=auth_key).user
if request.method == "POST" and generic_user:
#do whatever needed...
However the views is not reading the headers and throws an error. I could simply remove the Authentication/token line and voila! but the thing is that I want to keep the code as secure as possible.
What is wrong with my code?
I hope this codebase helps you to solve the problem.
async function sendBookingRequest() {
setIsLoading(true); // Start loading before making the request
try {
const response = await axios.post(
"https://danilo2588.pythonanywhere.com/book",
{
requested_date: date,
hours: bookedHours,
business: cancha,
phone: cellphone,
},
{
headers: {
Authorization: "1234567890123456789012345678901234567890",
},
}
);
setConfirmation(response.data); // Handle successful response
setStepper(7);
} catch (error) {
console.log(error); // Log or handle the error
} finally {
setIsLoading(false); // Stop loading after the request
}
}
And you can refer this documentation for axios configuration. https://axios-http.com/docs/post_example
Thanks