Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

req-ajax

Package Overview
Dependencies
Maintainers
1
Versions
9
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

req-ajax - npm Package Compare versions

Comparing version 1.2.0 to 2.0.0

src/ajax.js

100

dist/ajax.js
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
/*

@@ -10,35 +12,62 @@ * (c) Ricardo Moreno <morenoricardo237@gmail.com>

/**
* ajax - Standalone object for ajax request.
*
* @method query make a ajax request especific.
* @param {Object} config - object that represent the settings of the request.
* @property {String} url - the url of the request.
* @property {String} method - the method of the request.
* @property {Object} params - the parameters of the url.
* @property {String} fragment - the fragment of the url.
* @method get shorthand for make a ajax request with the method GET.
* @param {String|Object} url - string or object that represent the url.
* @property {String} url - the url of the GET request.
* @property {Object} params - the parameters of the url.
* @property {String} fragment - the fragment of the url.
* @param {Boolean} json - indicate if the response will be parse as json.
* @method post shorthand for make a ajax request with the method POST.
* @param {String|Object} url - string or object that represent the url.
* @property {String} url - the url of the request.
* @property {Object} params - the parameters of the url.
* @property {String} fragment - the fragment of the url.
* @param {String|Any} data - the data of the POST request.
* @param {Boolean} json - indicate if the request data will be parse as json.
*/
var ajax = {
xhr: function xhr() {
_createXHR: function _createXHR() {
try {
return new window.XMLHttpRequest();
} catch (err) {
throw err;
throw new Error('Error creating the XMLHttpRequest object');
}
},
_parseQuery: function _parseQuery(url, params, fragment) {
var uri = url;
query: function query(config) {
var xhr = this.xhr();
var url = config.url;
var method = config.method;
var params = config.params;
var fragment = config.fragment;
var query = url;
if (params) {
query += '?';
uri += '?';
for (var key in params) {
query += key + '=' + params[key] + '&';
uri += key + '=' + params[key] + '&';
}
query = query.replace(/&$/, '');
uri = uri.replace(/&$/, '');
}
if (fragment) {
query += '#' + fragment;
uri += '#' + fragment;
}
return uri;
},
query: function query(config) {
var xhr = this._createXHR();
var url = config.url,
method = config.method,
params = config.params,
fragment = config.fragment;
var query = this._parseQuery(url, params, fragment);
xhr.open(method, query, true);

@@ -57,9 +86,17 @@ xhr.send();

},
get: function get(url) {
var json = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var xhr = this.xhr();
var xhr = this._createXHR();
var method = 'GET';
xhr.open('GET', url, true);
if ((typeof url === 'undefined' ? 'undefined' : _typeof(url)) === 'object') {
var _url = url,
params = _url.params,
fragment = _url.fragment;
url = this._parseQuery(url.url, params, fragment);
}
xhr.open(method, url, true);
xhr.send();

@@ -80,12 +117,27 @@

},
post: function post(url, data) {
var json = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var xhr = this.xhr();
data = json ? JSON.stringify(data) : data;
var xhr = this._createXHR();
var method = 'POST';
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
var contentType = 'application/';
if ((typeof url === 'undefined' ? 'undefined' : _typeof(url)) === 'object') {
var _url2 = url,
params = _url2.params,
fragment = _url2.fragment;
url = this._parseQuery(url.url, params, fragment);
}
if (json) {
data = JSON.stringify(data);
contentType += 'json';
} else {
contentType += 'x-www-form-urlencoded';
}
xhr.open(method, url, true);
xhr.setRequestHeader('Content-Type', contentType);
xhr.send(data);

@@ -92,0 +144,0 @@

@@ -1,1 +0,1 @@

"use strict";var ajax={xhr:function(){try{return new window.XMLHttpRequest}catch(t){throw t}},query:function t(e){var s=this.xhr(),n=e.url,a=e.method,r=e.params,i=e.fragment,t=n;if(r){t+="?";for(var u in r)t+=u+"="+r[u]+"&";t=t.replace(/&$/,"")}return i&&(t+="#"+i),s.open(a,t,!0),s.send(),new Promise(function(t,e){s.onreadystatechange=function(){4===this.readyState?t(this.responseText):(403===this.status||404===this.status)&&e("Status code "+this.status)}})},get:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:!1,s=this.xhr();return s.open("GET",t,!0),s.send(),new Promise(function(t,n){s.onreadystatechange=function(){if(4===this.readyState){var s=this.responseText,a=e?JSON.parse(s):s;t(a)}else(403===this.status||404===this.status)&&n("Status code "+this.status)}})},post:function(t,e){var s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:!1,n=this.xhr();return e=s?JSON.stringify(e):e,n.open("POST",t,!0),n.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),n.send(e),new Promise(function(t,e){n.onreadystatechange=function(){4===this.readyState?t(this.responseText):(403===this.status||404===this.status)&&e("Status code "+this.status)}})}};
"use strict";var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ajax={_createXHR:function(){try{return new window.XMLHttpRequest}catch(t){throw new Error("Error creating the XMLHttpRequest object")}},_parseQuery:function(t,e,n){var r=t;if(e){r+="?";for(var s in e)r+=s+"="+e[s]+"&";r=r.replace(/&$/,"")}return n&&(r+="#"+n),r},query:function t(e){var n=this._createXHR(),r=e.url,s=e.method,a=e.params,o=e.fragment,t=this._parseQuery(r,a,o);return n.open(s,t,!0),n.send(),new Promise(function(t,e){n.onreadystatechange=function(){4===this.readyState?t(this.responseText):(403===this.status||404===this.status)&&e("Status code "+this.status)}})},get:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:!1,n=this._createXHR(),r="GET";if("object"===("undefined"==typeof t?"undefined":_typeof(t))){var s=t,a=s.params,o=s.fragment;t=this._parseQuery(t.url,a,o)}return n.open(r,t,!0),n.send(),new Promise(function(t,r){n.onreadystatechange=function(){if(4===this.readyState){var n=this.responseText,s=e?JSON.parse(n):n;t(s)}else(403===this.status||404===this.status)&&r("Status code "+this.status)}})},post:function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:!1,r=this._createXHR(),s="POST",a="application/";if("object"===("undefined"==typeof t?"undefined":_typeof(t))){var o=t,u=o.params,i=o.fragment;t=this._parseQuery(t.url,u,i)}return n?(e=JSON.stringify(e),a+="json"):a+="x-www-form-urlencoded",r.open(s,t,!0),r.setRequestHeader("Content-Type",a),r.send(e),new Promise(function(t,e){r.onreadystatechange=function(){4===this.readyState?t(this.responseText):(403===this.status||404===this.status)&&e("Status code "+this.status)}})}};

@@ -1,13 +0,11 @@

'use strict';
const fs = require('fs')
const path = require('path')
const fs = require('fs');
const path = require('path');
const gulp = require('gulp')
const babel = require('gulp-babel')
const uglyfly = require('gulp-uglyfly')
const dest = require('gulp-dest')
const gulp = require('gulp');
const babel = require('gulp-babel');
const uglyfly = require('gulp-uglyfly');
const dest = require('gulp-dest');
gulp.task('babel', function () {
gulp.src('./ajax.js')
gulp.src('./src/ajax.js')
.pipe(babel())

@@ -17,12 +15,14 @@ .pipe(gulp.dest('./dist'))

.pipe(dest('dist', { ext: '.min.js' }))
.pipe(gulp.dest('./'));
});
.pipe(gulp.dest('./'))
})
gulp.task('default', function () {
['js', 'min.js'].forEach(function (el) {
const pathFile = path.join(__dirname, `dist/ajax.${el}`);
let src = fs.readFileSync(pathFile).toString();
src = src.replace(/module\.exports(\W=\W|=)ajax;/, '');
fs.writeFileSync(pathFile, src);
});
});
gulp.task('removeCommonJS', function () {
['js', 'min.js'].forEach(function (ext) {
const pathFile = path.join(__dirname, `dist/ajax.${ext}`)
let src = fs.readFileSync(pathFile).toString()
src = src.replace(/module\.exports(\W=\W|=)ajax;/, '')
fs.writeFileSync(pathFile, src)
})
})
gulp.task('default', ['babel'])

@@ -1,1 +0,1 @@

module.exports = require('./ajax');
module.exports = require('./src/ajax')
{
"name": "req-ajax",
"version": "1.2.0",
"version": "2.0.0",
"description": "Standalone library for ajax requests",

@@ -5,0 +5,0 @@ "main": "index.js",

@@ -24,3 +24,3 @@ # req-ajax

## API
## API documentation

@@ -31,7 +31,8 @@ > All methods return a `Promise` object.

### `ajax.query(Object)`
### Method `query`
Declaratation: `ajax.query(config)`
the **Object** is the config of that request, this object can have 3 properties:
1. `url` **{String}** is required.

@@ -46,3 +47,3 @@ 2. `method` **{String}** is required.

ajax.query({
url: 'somepath',
url: '/somepath',
method: 'GET',

@@ -53,3 +54,3 @@ params: {

fragment: '123'
// the url should be 'somepath?foo=bar#123'.
// the uri should be '/somepath?foo=bar#123'.
}).then(function (res) {

@@ -62,4 +63,6 @@ // Do something with the response...

### `ajax.get(url [, json])`
### Method `get`
Declaratation: `ajax.get(url [, json])`
This method is an shorthand for **GET** requests.

@@ -69,3 +72,3 @@

1. `url` **{String}** is required.
1. `url` **{String|Object}** is required, `url` can be an object like in `ajax.query` but without the property `method`.
2. `json` **{Boolean}** is optional, default `false`. This param is for when the response is json string, if `json` is `true` the response is parser for convert it to a object normal.

@@ -76,3 +79,3 @@

```javascript
ajax.get('somefile.json', true)
ajax.get('/somefile.json', true)
.then(function (res) {

@@ -87,4 +90,6 @@ if (res.foo === 'bar') {

### `ajax.post(url, data [, json])`
### Method `post`
Declaratation: `ajax.post(url [, json])`
This method is an shorthand for **POST** requests.

@@ -94,4 +99,4 @@

1. `url` **{String}** is required.
2. `data` **{String|Number|Object|Boolean}** is required.
1. `url` **{String|Object}** is required, `url` can be an object like in `ajax.query` but without the property `method`.
2. `data` **{String|Any}** is required, if the paramater json is true, `data` can be anything.
3. `json` **{Boolean}** is optional, default `false`. This param is for when the data is object normal and will send it as a json string.

@@ -105,3 +110,3 @@

// The data is transformed to '{ "foo": "bar"}'
ajax.post('somepath', data, true)
ajax.post('/somepath', data, true)
.then(function ()

@@ -108,0 +113,0 @@ // The post request was complete.

@@ -1,69 +0,71 @@

'use strict';
'use strict'
const http = require('http');
const fs = require('fs');
const url = require('url');
const qs = require('querystring');
const path = require('path');
const http = require('http')
const fs = require('fs')
const url = require('url')
const qs = require('querystring')
const path = require('path')
const server = http.createServer();
const port = process.env.PORT || 8080;
const server = http.createServer()
const port = process.env.PORT || 8080
const html = fs.readFileSync(path.join(__dirname, 'index.html'));
const html = fs.readFileSync(path.join(__dirname, 'index.html'))
let items = ['ajax', 'request', 'server'];
let items = ['ajax', 'request', 'server']
server.listen(port, onListen);
server.on('request', onRequest);
server.listen(port, onListen)
server.on('request', onRequest)
function onRequest (req, res) {
let reqUrl = url.parse(req.url);
let reqUrl = url.parse(req.url)
if (reqUrl.pathname === '/') {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(html);
res.end();
res.writeHead(200, { 'Content-Type': 'text/html' })
res.write(html)
res.end()
} else if (reqUrl.pathname === '/data') {
res.writeHead(200);
res.write(items.toString().replace(/,/g, ' '));
res.end();
res.writeHead(200)
res.write(items.toString().replace(/,/g, ' '))
res.end()
} else if (reqUrl.pathname === '/post') {
req.on('data', function (chunk) {
let data = chunk.toString();
items.push(data);
res.writeHead(201);
res.end();
});
let data = chunk.toString()
items.push(data)
res.writeHead(201)
res.end()
})
} else if (reqUrl.pathname === '/delete') {
let query = qs.parse(reqUrl.query);
let index = parseInt(query.index);
let query = qs.parse(reqUrl.query)
let index = parseInt(query.index)
if (index >= 1) {
items.splice(index, index);
items.splice(index, index)
} else {
items.shift();
items.shift()
}
res.writeHead(200);
res.end();
} else if (reqUrl.pathname === '/test.json') {
let json = fs.readFileSync(path.join(__dirname, 'test.json'));
res.writeHead(200);
res.write(json.toString());
res.end();
res.writeHead(200)
res.end()
} else if (reqUrl.pathname === '/foo') {
let query = qs.parse(reqUrl.query)
let { file } = query
let json = fs.readFileSync(path.join(__dirname, file))
res.writeHead(200)
res.write(json.toString())
res.end()
} else if (reqUrl.pathname === '/json') {
req.on('data', function (chunk) {
let json = chunk.toString();
console.log(json);
});
res.writeHead(200);
res.end();
let json = chunk.toString()
console.log(json)
})
res.writeHead(200)
res.end()
} else if (reqUrl.pathname === '/test.js') {
let js = fs.readFileSync(path.join(__dirname, 'test.js'));
res.write(js);
res.end();
let js = fs.readFileSync(path.join(__dirname, 'test.js'))
res.write(js)
res.end()
} else if (reqUrl.pathname === '/ajax.js') {
let ajax = fs.readFileSync(path.resolve(__dirname, '../dist/ajax.js'));
res.write(ajax);
res.end();
let ajax = fs.readFileSync(path.resolve(__dirname, '../dist/ajax.js'))
res.write(ajax)
res.end()
}

@@ -73,4 +75,4 @@ }

function onListen () {
console.log('The server test is running.');
console.log(`Please open your browser at http://localhost:${port}.`);
console.log('The server test is running.')
console.log(`Please open your browser at http://localhost:${port}.`)
}

@@ -41,3 +41,3 @@ window.onload = function () {

$btnGetJSON.onclick = function () {
ajax.get('/test.json', true)
ajax.get({ url: '/foo', params: { file: 'test.json' } }, true)
.then(function (res) { $getJSON.textContent = JSON.stringify(res); })

@@ -44,0 +44,0 @@ .catch(function (err) { console.log(err); });

{
"foo": "bar"
"foo": "bar",
"bar": "foo"
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc