import {IRequestOptions} from "../IRequestOptions"; import {globalSetupOptions} from "../globalSetup"; import {encodeParam} from "../URLUtils"; import {IParamsObject} from "../IParamsObject"; /** * * Post * Content-Type application/x-www-form-urlencoded * * */ export function postFormURLEncoded(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)); } } } xhr.open('POST', path); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); if(globalSetupOptions.beforeEachRequest) { globalSetupOptions.beforeEachRequest(xhr); } if(options) { if(options.beforeSend) { options.beforeSend(xhr); } } if(!data) { data = {}; } xhr.send(encodeParam(data)); }); }