1.0.0-alpha • Published 2 years ago

typescript-request v1.0.0-alpha

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

typescript-request

Typescript library to easy use XMLHttpRequest

Installation

npm install typescript-request

How to use directly in HTML project

<!DOCTYPE html>
<html>
<head>
    <!-- USE LINES ABOVE IF Uncaught ReferenceError: exports is not defined IN CONSOLE -->
    <!-- DO NOT USE THIS IN WEBPACK or GULP BROWSERIFY/TSIFY PROJECTS -->
    <script>
        var exports = {};
    </script>
    <!-- END USE -->
    <!-- END THIS ERROR -->

    <script src="lib/request.js"></script>

    <script>
        const successUrl = 'https://github.com/djpatzo/typescript-request/success-request.json';
        const errorUrl = './not-exists.json';

        window.addEventListener('load', function() {
            document.write('<h4>Check developers console!!!</h4>')
            /**
             * Success request
             */
            new TSRequest(successUrl, 'GET', [], {
                onReady: function (responseData) {
                    console.info('Ready success', responseData);
                },
                onSuccess: function(responseData) {
                    console.log('Success', responseData);
                }
            });

            /**
             * Error request
             */
            new TSRequest(errorUrl, 'GET', [], {
                onReady: function (responseData) {
                    console.info('Ready error');
                },
                onError: function (responseData) {
                    console.error('Error');

                    //document.write('Error: ', JSON.stringify(responseData));
                }
            });
        });
    </script>
</head>
<body>
</body>
</html>

How to use in TypeScript Project

import TSRequest from 'typescript-request';

const url: string = 'https://github.com/djpatzo/typescript-request/success-request.json';

new TSRequest(successUrl, 'GET', [], {
  onReady: function (responseData) {
    console.info('Ready success');
  },
  onSuccess: function(responseData) {
    console.log('Success', responseData);
  }
});

Initialization

TSRequest(..arguments)TypeDescription
urlstring (required)Required. The 'url' is required to make request
methodstring (default:'GET')Optional. If you want to set headers or options, you must set this string. Available are standard HTTP methods, eg. GET, POST, PUT, DELETE, etc.
headersArray\ (default:[])Optional. See src/HeadersInterface.ts Every item in array must be object with name and value keys. Here we must use standard HTTP Headers. Eg. { name: 'Header-Name', value: 'Value of header' }, { name: 'Header-Name-2', value: 'Value of header 2' }
optionsobject (default:{}) see options parametersOptional. Every item in array must be object with name and value keys. Here we must use standard HTTP Headers. Eg. { name: 'Header-Name', value: 'Value of header' }, { name: 'Header-Name-2', value: 'Value of header 2' }

options

By default, TSRequest uses only four parameters

const defaultOptions: any = {
  postData: null,
  onReady: null,
  onError: null,
  onSuccess: null
};

options parameters

postData is required only with method 'POST' in constructor

onReady is executed everytime where XMLHttpRequest readyState is 4 (end request)

onSuccess is executed everytime where HTTP Response Code is 200

onError is executed everytime where HTTP Response Code is not 200

ababagent-baseansi-escapesansi-regexansi-stylesanymatchasynckitacorn-walkargparsebabel-plugin-istanbulacornbalanced-matchacorn-globalsbrace-expansionbabel-preset-current-node-syntaxbracesbrowser-process-hrtimebs-loggerbabel-jestbabel-preset-jestbuffer-fromcallsitesbabel-plugin-jest-hoistcamelcasechar-regexbrowserslistchalkci-infocjs-module-lexercliuicocollect-v8-coveragecolor-convertcolor-namecombined-streamcommanderconcat-mapconvert-source-mapbsercross-spawncssomcssstyledata-urlscaniuse-litedebugdecimal.jsdedentdeepmergebuiltin-modulesdelayed-streamdetect-newlinediffdiff-sequencesdomexceptionemitteryemoji-regexescaladeescape-string-regexpesprimaexecaelectron-to-chromiumescodegenexitdeep-isexpectfast-json-stable-stringifyfast-levenshteinfb-watchmanfill-rangefind-upfs.realpathform-datafunction-bindgensyncget-caller-fileesutilsget-streamestraverseglobalsglobhashas-flaghtml-encoding-sniffergraceful-fshttp-proxy-agenthttps-proxy-agenthuman-signalsiconv-liteimport-localget-package-typeimurmurhashinflightinheritsis-core-moduleis-fullwidth-code-pointis-generator-fnis-numberis-streamis-potential-custom-element-namehtml-escaperis-typedarrayisexeistanbul-lib-instrumentistanbul-lib-coverageistanbul-lib-reportistanbul-lib-source-mapsistanbul-reportsjest-changed-filesjest-circusjest-clijest-configjest-diffjest-eachjest-docblockjest-environment-jsdomjest-environment-nodejest-get-typejest-haste-mapjest-jasmine2jest-leak-detectorjest-matcher-utilsjest-message-utiljest-mockjest-pnp-resolverjest-resolvejest-regex-utiljest-runnerjest-resolve-dependenciesjest-runtimejest-serializerjest-snapshotjest-validatejest-utiljest-watcherjest-workerjs-tokensjs-yamljsdomjsescjson5kleurlevenlocate-pathlodashlodash.memoizelru-cachemake-errormakeerrormerge-streammicromatchmime-dbmime-typeslevnmimic-fnminimatchminimistmake-dirmkdirpmsnode-modules-regexpnatural-comparenormalize-pathnpm-run-pathnwsapionceonetimep-limitp-locatep-trypath-existsnode-int64parse5path-is-absolutepath-keyoptionatorpicomatchnode-releasespiratespkg-dirpretty-formatpromptspslreact-ispath-parserequire-directoryresolveresolve-cwdresolve.exportsresolve-frompicocolorsrimrafpunycodesafe-bufferprelude-lssafer-buffersaxessemvershebang-commandshebang-regexsignal-exitslashsource-mapsource-map-supportstack-utilsstring-lengthstring-widthstrip-ansistrip-bomstrip-final-newlinesisteransisupports-colorsupports-hyperlinkssprintf-jssymbol-treeterminal-linkthroattmplto-fast-propertiesto-regex-rangetr46tough-cookietslibtsutilstype-detecttypedarray-to-buffertype-festuniversalifyv8-to-istanbulw3c-hr-timew3c-xmlserializerwalkerwebidl-conversionswhatwg-encodingtest-excludetype-checkwhatwg-mimetypewhatwg-urlwhichwrap-ansiwrappywrite-file-atomicwsxml-name-validatorxmlcharsy18nyallistyargsyargs-parserword-wrap
1.0.0-alpha

2 years ago

1.0.0

2 years ago