如何使用 Fetch 和 Ajax 将身份验证令牌从前端发送到 Restful API 后端?

问题描述 投票:0回答:1

我目前正在与 django Restframwork 合作,我正在接受培训。我使用 DRF 创建了一个用于彩票管理系统的 api,并在这个宁静的 api 中添加了

IsAuthenticated
权限类。现在我正在为此 api 创建演示项目,现在我使用 ajax 进行请求并使用 btoa 发送授权。但我确信这不是专业的方法。我想了解如何使用用户名和密码将授权令牌发送到后端。以及如何在reactjs中实现相同的目标,因为我对react js有点熟悉并也在研究它。


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);
    },
  });
}
javascript python reactjs django django-rest-framework
1个回答
0
投票

使用 AJAX:

1 - 获取令牌:使用您的用户名和密码进行身份验证以获取令牌。

2 - 修改AJAX调用:

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

将 React 与 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();
}
© www.soinside.com 2019 - 2024. All rights reserved.