/** * User GET method * */ import {IRequestOptions} from "../IRequestOptions"; import {IParamsObject} from "../IParamsObject"; import {addURLParam} from "../URLUtils"; import {globalSetupOptions} from "../globalSetup"; export function getData(path: string, data: IParamsObject|null, options?: IRequestOptions): Promise { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if(xhr.readyState === 4) { if(globalSetupOptions.afterEachRequest) { globalSetupOptions.afterEachRequest(xhr); } if(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) { if(/application\/json/.test(xhr.getResponseHeader('Content-Type'))) { resolve(JSON.parse(xhr.responseText)); } else { resolve(xhr.responseText); } } else { reject(new Error('xhr failed: ' + xhr.status)); } } } if(data) { path = addURLParam(path, data); } xhr.open('GET', path); if(globalSetupOptions.beforeEachRequest) { globalSetupOptions.beforeEachRequest(xhr); } if(options) { if(options.beforeSend) { options.beforeSend(xhr); } } xhr.send(null); }); }