jsRequest/Request.js

125 lines
3.4 KiB
JavaScript

export const getCsrf = ( name = "X-CSRF-TOKEN") => {
const $meta = document.querySelector(`meta[name="${name}"]`);
const content = $meta.getAttribute("content");
const obj = {};
obj[name] = content;
return obj;
}
const getFetchHeaders = () => {
return {
...getCsrf(),
"X-Requested-Width": "XMLHttpRequest"
}
}
const getFetchConfig = () => {
return {
headers: getFetchHeaders(),
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
redirect: 'follow',
referrerPolicy: 'no-referer'
}
}
const transArray = (name, arr) => {
return arr.map((val) => `${name}[]=${val}`).join('&');
}
const transSearchParams = (data) => {
let str = "";
for (const[key, value] of Object.entries(data)) {
if (Array.isArray(value)) {
str += `${encodeURIComponent(key)} = ${encodeURIComponent(value)}`;
}
}
return str;
}
export class Form {
static _createInput = (name, value, type = 'text') => {
const oInput = document.createElement("input");
oInput.setAttribute('type', type);
oInput.setAttribute('name', name);
oInput.setAttribute('value', value);
return oInput;
}
static post(url, data) {
const oForm = document.createElement('form');
Object.entries(data).forEach(([name, value]) => {
oForm.append(Form._createInput(name, value));
});
const oCsrf = getCsrf();
const sCsrfName = Object.keys(oCsrf)[0];
const sCsrfValue = oCsrf[sCsrfName];
oForm.append(Form._createInput(sCsrfName,sCsrfValue));
oForm.style.display = 'none';
oForm.setAttribute('method', 'post');
oForm.setAttribute('action',url);
document.append(oForm);
oForm.submit();
}
static get(url, data) {
const oForm = document.createElement('form');
Object.entries(data).forEach(([name, value]) => {
oForm.append(Form._createInput(name, value));
});
const oCsrf = getCsrf();
const sCsrfName = Object.keys(oCsrf)[0];
const sCsrfValue = oCsrf[sCsrfName];
oForm.append(Form._createInput(sCsrfName,sCsrfValue));
oForm.style.display = 'none';
oForm.setAttribute('method', 'get');
oForm.setAttribute('action',url);
document.append(oForm);
oForm.submit();
}
}
export const Upload = (url, data, file) => {
const formData = new FormData();
formData.append('image', file);
Object.entries(data).forEach(([k,v]) => { formData.append(k,v) });
return $.ajax({
url,
cache: false,
constentType: false,
processData: false,
method: 'POST', //method for newer jQuery versions, type for older one thx @ Marian Haller
type: 'POST',
'headers': getCsrf(),
data: formData
});
}
export const Post = (url, data) => {
const headers = {...getCsrf()},
return $.ajax({
url,
data,
method: 'POST', //method for newer jQuery versions, type for older one thx @ Marian Haller
type: 'POST',
headers
});
}
export const Get = (url, data) => {
const headers = {...getCsrf()},
return $.ajax({
url,
data,
method: 'GET', //method for newer jQuery versions, type for older one thx @ Marian Haller
type: 'GET',
headers
});
}