I am currently working with django restframwork, I am on my training period. I created a api for lottery management system using DRF and in this restful api i added IsAuthenticated
permission class. Now i am creating demo project for this api, now i am using ajax for requests & sending authorization using btoa. but i am sure that this is not a professional method. I wanted to learn how to send the authorization token to backend with username and password. & also how to achieve same in reactjs as i am little bit familiar with react js and working on it as well.
function ajaxCall(type, url, data, callback) {
/**Common Method to handle all the Ajax Requests */
$.ajax({
url: url,
type: type,
data: data,
headers: {
"Authorization": "Basic " + btoa(USERNAME + ":" + PASSWORD)
},
success: function (response, status, xhr) {
console.log(response);
console.log(xhr);
if (xhr.status != 204) {
if (callback) {
callback(response);
}
}
},
error: function (xhr, status, error) {
console.error("Error occurred:", xhr.responseText, status, error);
},
});
}
2
Answers
Using AJAX:
1 – Obtain the Token: Authenticate with your username and password to get a token.
2 – Modify AJAX Call:
Using React with Fetch:
Sample Login API Response:
Success (200 OK):
Error (401 Unauthorized):
To send an authentication token from the frontend to a RESTful API backend using both Fetch and Ajax, you can follow the steps below.
Using Fetch API
Using jQuery Ajax
I hope this example code helped you. 🙂