Promise based simple HTTP/HTTPS client for browser to request JSON or string for RESTful apis, with koa-like middleware support.
npm install req-json --save
import ReqJSON from 'req-json';
Direct <script>
include
<script src="https://cdn.jsdelivr.net/npm/req-json@2"></script>
const ReqJSON = require('req-json/dist/req-json.wx');
or just download and copy to your project.
import ReqJSON from 'req-json';
const reqJSON = new ReqJSON();
reqJSON.get('/api/item/:id', { id: 1 })
.then((item) => {});
async getItem(id) {
let item;
try {
item = await reqJSON.get('/api/item/:id', { id });
} catch (err) {
console.error(err);
}
return item;
}
async updateItem(item) {
try {
await reqJSON.post('/api/item/:id', item);
} catch (err) {
console.error(err);
}
}
const resource = reqJSON.resource('/api/item/:id');
async getItem(id) {
let item;
try {
item = await resource.get({ id });
} catch (err) {
console.error(err);
}
return item;
}
async updateItem(item) {
try {
await resource.post(item);
} catch (err) {
console.error(err);
}
}
Supports GET
POST
PUT
DELETE
methods.
const resource = reqJSON.resource('/api/item/:id');
async request() {
try {
const response = await resource.get({ id: 1 });
await resource.post({
id: 1,
others: { foo: 'bar' }
});
await resource.put({
id: 1,
others: { foo: 'bar' }
});
await resource.delete({ id: 1 });
} catch (err) {
console.error(err);
}
}
You can set option for ReqJSON instance / resource defination / each single request.
headers
: Customized request headerstimeout
: Set request timeout
const options = {
headers: {
Authorization: 'abc'
},
timeout: 1000
};
const reqJSON = new ReqJSON(options);
const options = {
headers: {
Authorization: 'abc'
},
timeout: 1000
};
const resource = reqJSON.resource('/api/item/:id', options);
async request() {
try {
await resource.get({ id: 1 });
} catch (err) {
console.error(err);
}
}
async request() {
const options = {
headers: {
Authorization: 'abc'
},
timeout: 1000
};
try {
await resource.get({ id: 1 }, options);
} catch (err) {
console.error(err);
}
}
Supports two diffrent kinds of functions as middleware:
- async function
- common function
Async function (Can I use)
reqJSON.use(async(context, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
console.log(`${context.method} ${context.url} ${ms}ms`);
});
reqJSON.use((context, next) => {
const start = Date.now();
return next()
.then(() => {
const ms = Date.now() - start;
console.log(`${context.method} ${context.url} ${ms}ms`);
});
});
Context contains these attributes:
/**
* The path to use for the request, with parameters defined.
*/
path: string
/**
* The HTTP method to use for the request (e.g. "POST", "GET", "PUT", "DELETE").
*/
method: 'POST' | 'GET' | 'PUT' | 'DELETE'
/**
* The URL to which the request is sent.
*/
url: string
/**
* The data to be sent.
*/
data: any
/**
* The options to use for the request.
*/
options: object
/**
* The HTTP status of the response. Only available when the request completes.
*/
status?: number
/**
* The parsed response. Only available when the request completes.
*/
response?: any
/**
* The request headers before the request is sent, the response headers when the request completes.
*/
headers: Headers
/**
* Alias to `headers`
*/
header: Headers
/**
* The original XMLHttpRequest object.
*/
xhr: XMLHttpRequest
reqJSON.use(async(context, next) => {
await next();
if (context.status >= 400) {
throw new Error(context.response);
}
});
reqJSON.use((context, next) => {
return next()
.then(() => {
if (context.status >= 400) {
throw new Error(context.response);
}
});
});
reqJSON.use(async(context, next) => {
// set request headers
context.headers = {
'If-None-Match': 'abcdefg'
};
await next();
// get response headers
console.log(context.headers.etag);
});
reqJSON.use((context, next) => {
// set request headers
context.headers = {
'If-None-Match': 'abcdefg'
};
return next()
.then(() => {
// get response headers
console.log(context.headers.etag);
});
});