我目前正在与 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);
},
});
}
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);
},
});
}
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();
}