fix: and use axios

This commit is contained in:
starnakin 2023-11-13 13:27:37 +01:00
parent 2ceb036c2f
commit 6ea2f25f7f
2 changed files with 21 additions and 46 deletions

View File

@ -1,16 +1,14 @@
import axios from "axios";
axios.defaults.xsrfCookieName = 'csrftoken';
axios.defaults.xsrfHeaderName = 'X-CSRFToken';
axios.defaults.withCredentials = true;
/** /**
* return the token from response * return the token from response
* *
* @param {Response} response - The reponse * @param {Response} response - The reponse
*/ */
function extract_csrf_token(response)
{
let cookies = response.headers.get("set-cookie");
csrf_token = cookies.slice(cookies.indexOf("=") + 1, cookies.indexOf(';'))
return csrf_token;
}
class Client class Client
{ {
/** /**
@ -22,24 +20,14 @@ class Client
constructor(url) constructor(url)
{ {
/** /**
* The api token to be logged * The axios client
* @type string */ * @type AxiosInstance */
this.token = undefined; this.client = axios.create({
baseURL: url,
/** headers: {
* The django csrftoken to send post data 'Content-Type': 'application/json'
* @type string */ }
this.csrf_token = undefined; });
/**
* The django csrfmiddlewaretoken to send post data
* @type string */
this.csrfmiddlewaretoken = undefined
/**
* The api url
* @type string */
this.url = url;
} }
/** /**
@ -57,9 +45,7 @@ class Client
*/ */
async _get(uri) async _get(uri)
{ {
let url = this.url + uri let response = await this.client.get(uri);
let response = await fetch(url);
this.csrf_token = extract_csrf_token(response);
return response; return response;
} }
@ -71,20 +57,10 @@ class Client
async _post(uri, data) async _post(uri, data)
{ {
/** /**
* @type string */ * The axios client
let url = this.url + uri * @type AxiosInstance */
if (this.csrf_token === undefined) console.log(data)
{ let response = await this.client.post(uri, data)
let response = await fetch(url);
this.csrf_token = extract_csrf_token(response);
}
let response = await fetch(url, {
method: "POST",
headers: {
'Referer': url,
},
body: objectToFormData(data),
});
console.log(response.status) console.log(response.status)
return response; return response;
} }
@ -97,7 +73,7 @@ class Client
*/ */
async login(username, password) async login(username, password)
{ {
let response = this._post(accounts_login, {'username': username, 'password': password}) let response = this._post(accounts_login, {username: username, password: password})
return response; return response;
} }
} }
@ -108,7 +84,6 @@ let url = "http://0.0.0.0:8000/"
let client = new Client(url) let client = new Client(url)
await client._get(accounts_login) let response = await client.login("bozoman", "man")
await client.login("bozoman", "man")
export {Client} export {Client}

View File

@ -1,4 +1,4 @@
let api = "api/" let api = ""
let accounts = api + "accounts/" let accounts = api + "accounts/"
let accounts_register = accounts + "register" let accounts_register = accounts + "register"