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);
},
});
}
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
// Assuming the token is stored in localStorage after login
const token = localStorage.getItem('authToken');
fetch('https://api.example.com/endpoint', {
method: 'GET', // or 'POST', 'PUT', etc.
headers: {
'Authorization': `Bearer ${token}`, // Structure depends on your API
'Content-Type': 'application/json'
}
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
console.log('Success:', data);
})
.catch(error => {
console.error('Error:', error);
});
Using jQuery Ajax
// Assuming the token is stored in localStorage after login
const token = localStorage.getItem('authToken');
$.ajax({
url: 'https://api.example.com/endpoint',
type: 'GET', // or 'POST', 'PUT', etc.
headers: {
'Authorization': `Bearer ${token}` // Structure depends on your API
},
dataType: 'json',
success: function(data) {
console.log('Success:', data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.error('Error:', errorThrown);
}
});
I hope this example code helped you. 🙂
4