How to Send Authentication Token from Frontend using Both Fetch & Ajax to Restful API Backend?

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);
    },
  });
}

Using AJAX:

1 - Obtain the Token: Authenticate with your username and password to get a token.

2 - Modify AJAX Call:

function ajaxCall(type, url, data, token, callback) {
  $.ajax({
    url: url,
    type: type,
    data: data,
    headers: {
      "Authorization": "Token " + token
    },
    success: function (response) {
      if (callback) callback(response);
    },
    error: function (xhr) {
      console.error("Error:", xhr.responseText);
    },
  });
}

Using React with Fetch:

async function fetchWithToken(url, method, data, token) {
  const response = await fetch(url, {
    method: method,
    headers: {
      "Content-Type": "application/json",
      "Authorization": "Token " + token
    },
    body: JSON.stringify(data),
  });
  return response.json();
}

Sample Login API Response:

Success (200 OK):

{
  "user": {
    "id": 1,
    "username": "your_username",
    "email": "your@email.com"
  },
  "token": "eyJ0eXAiOiJKV1QiLCJh... (JWT token)"
}

Error (401 Unauthorized):

{
  "detail": "Invalid username or password."
}

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. :)

Back to Top