The reason
In fact, if you work for a long time, you will have a lot of thinking. As a front end, what we actually touch most is the API that is relevant to the business in addition to JS code.
And as a pursuing front end, have you ever thought about writing for so many years and building a few wheels yourself? The API, we have to take somebody else’s package every time. It’s just fast, use, wonder if we need him or not. What’s the point of bringing in someone else’s third-party stuff besides making it easier for your project?
If you’re a C-side (performance, SEO, optimization) project, you’ve probably thought about how to optimize your code.
But: the best optimization is to do subtraction
Back to business: Do we need Axios, or jquery?
The core reason jquery was killed in the first place was the advent of angularJS and the beginning of front-end rendering pages. But jquery is still around, and I still use it when I switched to front-end in 18. But INSTEAD of using $(‘class or ID’), I just use ajax. Then axios came along. Why axios? Because Axios is small, it takes up little resources.
Then I thought about wrapping an HTTP request function myself. Later I compared Axios (12KB) to jquery (90KB), but we used only a fraction of the resources. Is it really necessary? That’s a matter of opinion.
My main purpose today is to get to know myself, and to use my own encapsulated function in future projects. 12KB is still a lot, don’t you think?
Understand XMLHttpRequest
This API, while somewhat complex overall, has been with the front end for nearly 20 years (it wasn’t named that way before, so don’t get hung up on it). Ajax was a milestone in the rise of the front end.
MDN Reference link: developer.mozilla.org/zh-CN/docs/…
However, the API definition is really cumbersome, and our custom is to pass values in JSON mode, which is ajax in the era of jquery
Specific documents we see, we actually need to use the core is
let xhr = new XMLHttpRequest()
// End of request
xhr.onloadend
// Request error
xhr.onerror
// The request timed out
xhr.ontimeout
// Open the request
xhr.open(method as string, url as string, true)
// Set the desired return data type
XHR. ResponseType = “json”
// Set the request header
xhr.setRequestHeader(key, header[key])
// Send the request
xhr.send(null)
Above IE10, we only need to focus on the OnLoadEnd part. When the request succeeds, the parameters are returned, and on is the callback function
As you can see, the code is very simple, and that’s probably all we’re used to. But native to write, certainly very troublesome.
So everybody’s going to encapsulate it again
Here’s a very nice tutorial from The Simple Book: XMLHttpRequest – Always Know, always know
Two, whether to use TS
In fact, I also thought a lot, in the end, actually did not understand. But I did.
Iii. Finished product code
Project git address: github.com/ht-sauce/dh…
The uncompiled and packaged files are ajax. ts under SRC, and the packaged files are in the Ajax directory, where the index.js file is compressed and packaged and can be used directly with the script tag.
Interface Config {prefix? : string // prefix URL? : string // Path data? : any // The passed parameter method? : string splicing? : Boolean // Whether to concatenate data timeout under get request? : number type? : string // Data response type header? : object | any} / / buried point report file class Ajax {/ / private variable part private _xhr: XMLHttpRequest constructor() {this._xhr = {} as XMLHttpRequest} // Abort interface request () {this._xhr && this._xhr.abort()} Private splicing(data: any): string { let params = '' for (const key in data) { params += `${key}=${data[key]}&` } params = '? '+ params.substring(0, params. length-1) return params} private config({prefix = '', url = '', Data = {}, method = 'get', splicing = true, timeout = 1000 * 30, // default wait 1 min type = 'json', header = {' content-type ': 'application/json; charset=UTF-8', }, }: Config): Url = prefix + url if (method === 'GET' &&splicing) URL = URL + this.splicing(data) const config = { prefix, url, data, splicing, method, timeout, type, header, } return config} // image request mode image(config: config) : void {const setting: config = this.config(config) let image: HTMLImageElement | null image = new image (image). The SRC = setting. The url as a string image = null} / / / / to empty memory XHR requests request(config: Config): Promise<any> { const { url, method, timeout, header, type } = this.config(config) let xhr: XMLHttpRequest if (window.XMLHttpRequest) xhr = new XMLHttpRequest() this._xhr = xhr! Return new promise ((resolve, reject) => {if (! XHR) reject(' version not supported ') // Request success callback function // xhr.onload = e => {// //console.log('load', Xhr.onloadend = e => {const status = xhr.status let data if (xhr.responseType === 'text') { data = xhr.responseText } else if (xhr.responseType === 'document') { data = xhr.responseXML } else { data = xhr.response } resolve({ data, status, xhr: Xhr. onerror = e => {//console.error('error', E) reject(e)} xhr.ontimeout = e => {//console.error('timeout', E) reject(e)} // Xhr. onabort = e => {// reject(e) //} xhr.open(method as string, url as string, True) / / set the desired XHR return data type. The responseType = type as XMLHttpRequestResponseType / / set the request header for (const key of Object.keys(header)) { xhr.setRequestHeader(key, Header [key])} xhr.send(null) xhr.timeout = timeout as number})} // FETCH () {} // _success() {} // _error() {}} export default AjaxCopy the code
Use:
const ajax = new Ajax()
interface Ceshi {
ceshi: string
dht: number
}
const one = () => {
ajax
.request({
url: '/test/one',
data: {
ceshi: '11111',
dht: 12321,
} as Ceshi,
})
.then(e => {
console.log(e)
})
.catch(e => {
console.log(e)
})
}
Copy the code
Fetch
MDN address: developer.mozilla.org/zh-CN/docs/…
In fact, if your project doesn’t have any IE requirements, use FETCH. It’s good. You just need to wrap according to your business.
In fact, in addition to writing this, I have always wanted to implement, but also to learn how to use rollup.
And then there’s the little show off. I find Nest a little simple. It took me half an hour to write the interface with Nest for the test.