ajax-client

A simple ajax client with jQuery like ajax API for js.
jQuery is great, but do you use jQuery(80KB over) only for ajax?
install
npm install ajax-client
and write followings in your code
- AjaxClient is based on the XmlHttpRequest2 and HAS APIs most similar to jQuery's API
import {AjaxClient} from 'ajax-client'
client.ajax({
type: 'post',
url: 'http://localhost:9999/api',
headers: {
'X-Original-Header1': 'header-value-1',
'X-Original-Header2': 'header-value-2',
},
contentType: 'application/json',
data: JSON.stringify(data),
dataType: 'json',
timeoutMillis: 5000,
success: (response, xhr) => {
},
error: (e, xhr) => {
},
timeout: (e, xhr) => {
}
});
- AjaxClient2(recommended) is base on fetch API
import {AjaxClient2 as AjaxClient} from 'ajax-client'
import ajax_client from 'ajax-client';
const { AjaxClient2 } = ajax_client;
<script src="https://cdn.jsdelivr.net/npm/ajax-client@2.0.2/lib/ajax-client.min.js"></script>
usage
Post
- Post JSON string to server,Receive JSON string from server.
const client = new AjaxClient2();
const data = {
message: "hello"
}
client.ajax({
type: 'post',
url: 'http://localhost:9999/api',
headers: {
'X-Original-Header1': 'header-value-1',
'X-Original-Header2': 'header-value-2',
},
contentType: 'application/json',
data: JSON.stringify(data),
dataType: 'json',
timeoutMillis: 5000,
success: (data, response) => {
},
error: (data,response,cause,err) => {
},
timeout: (data,response,cause,err) => {
}
});
const client = new AjaxClient2();
const data = {
message: "hello"
}
client.ajax({
type: 'post',
url: `http://localhost:${serverPort}/form`,
headers: {
'X-Original-Header1': 'header-value-1',
'X-Original-Header2': 'header-value-2',
},
contentType: 'application/x-www-form-urlencoded',
data,
dataType: 'json',
timeoutMillis: 5000,
success: (data, response) => {
},
error: (data,response,cause,err) => {
},
timeout: (data,response,cause,err) => {
}
});
Post with done/fail
client.ajax({
type: 'post',
url: 'http://localhost:9999/api',
dataType: 'text',
timeoutMillis: 5000,
}).done((data,response) => {
console.log(data);
console.log(response.status);
}).fail((data,response,cause,err) => {
console.log(data);
console.log(response.status);
});
Post with Async/Await
const client = new AjaxClient2();
const result = await client.post({
url: 'http://localhost:9999/api',
headers: {
'X-Original-Header1': 'header-value-1',
'X-Original-Header2': 'header-value-2',
},
contentType: 'application/json',
data: data,
dataType: 'json',
timeoutMillis: 5000,
});
console.log(result.success);
console.log(result.data);
console.log(result.response.status);
Success Response
{
success: true,
data:{ },
response:{},
}
Error Response
Occurs when the server side returns a status code other than 200-299.
Parse the error object yourself if you want to determine more details.
{
success: false;
data:{ },
cause:'server error,statusCode:404',
error:e,
response:{},
}
When you specify json as the expected data type, but the server returns text, etc.
Parse the error object yourself if you want to determine more details.
{
success: false;
data:{ },
cause:'client error,${error_message_thrown_at_client}',
error:e,
response:{},
}
Occurs when the network is disconnected or the server cannot be found.
Parse the error object yourself if you want to determine more details.
{
success: false;
data:null,
cause:'network error',
error:e,
response:null,
}
{
success: false;
data:null,
cause:'timeout,100ms elapsed',
error:e,
response:null,
}
Get
const client = new AjaxClient2();
client.ajax({
type: 'get',
url: 'http://localhost:9999/something.html',
dataType: 'text',
timeoutMillis: 5000,
success: (data, response) => {
},
error: (data,response,cause,err) => {
},
timeout: (data,response,cause,err) => {
}
});
console.log(result.success);
console.log(result.data);
console.log(result.response.status);
Get with Async/Await
const client = new AjaxClient2();
const result = await client.get({
url: 'http://localhost:9999/api',
headers: {
'X-Original-Header1': 'header-value-1',
'X-Original-Header2': 'header-value-2',
},
dataType: 'text',
timeoutMillis: 5000,
});
Success Response
{
success: true,
data:{ },
response:{},
}
Error Response
{
success: false;
cause:'error',
error:e,
response:{},
}
{
success: false;
cause:'timeout',
error:e,
response:null,
}
Example (using ajax-client)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajax-client example</title>
</head>
<body>
<script src="https://raw.githubusercontent.com/riversun/ajax-client/master/dist/ajaxclient.js"></script>
<script>
const ajax = new AjaxClient2();
const data = {
message: "hello"
}
ajax.postAsync({
url: 'http://localhost:9999/api',
headers: {
'X-Original-Header1': 'header-value-1',
'X-Original-Header2': 'header-value-2',
},
contentType: 'application/json; charset = UTF-8',
data: JSON.stringify(data),
dataType: 'json',
timeoutMillis: 5000,
success: response => {
console.log(response);
},
error: e => {
console.error('Error occurred');
},
timeout: e => {
console.error('Timeout occurred.');
}
});
</script>
</body>
</html>
Run on node.js (ES6 -)
If you set up node-fetch
externally, you can use AjaxClient with node.js.
import fetch from 'node-fetch';
import ajax_client from 'ajax-client';
const { AjaxClient2 } = ajax_client;
const ajax = new AjaxClient2({ fetch });
Run on node.js (commonJS/babel)
If you set up node-fetch
externally, you can use AjaxClient with node.js.
import fetch from 'node-fetch';
import { AjaxClient2 as AjaxClient } from 'ajax-client';
const ajax = new AjaxClient({ fetch });
Run test server (node.js)
- run test-server to test example above
TestServer.js
npm run test-server
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
var port = process.env.PORT || 9999;
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin,Content-Type,Accept,X-Original-Header1,X-Original-Header2");
next();
});
app.post('/api', bodyParser.json(), function (req, res, next) {
res.status(200);
const data = req.body;
if (data) {
let message = "Hi,there! You say " + data.message;
res.json({
output: message
});
} else {
let message = 'error:message not found.';
res.json({
error: message
});
}
});
app.listen(port);
console.log('Server started on port:' + port);
Classical approach(using jQuery)
index_jquery.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery ajax example</title>
</head>
<body>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script>
const data = {
message: "hello"
}
$.ajax({
type: "post",
url: 'http://localhost:9999/api',
headers: {
'X-Original-Header1': 'header-value-1',
'X-Original-Header2': 'header-value-2',
},
contentType: 'application/json; charset = UTF-8',
data: JSON.stringify(data),
dataType: "json",
success: response => {
console.log(response);
},
error: e => {
console.error('Error occurred');
}
});
</script>
</body>
</html>