Practice the way js 8 initiates http requests

Preface

In the past two days, when I was writing the login at the company, I found that I almost forgot the fetchrequest and the original implementation request method. It is estimated that I have not read it for too long. I will record the method of initiating the http request here, so that I can check it later.

1. Native request

Although we rarely use native ajax in real project development, we still need to know how to write native ajax.

let xhr = new XMLHttpRequest();
xhr.open('GET','url',true);
xhr.onReadyState(()=>{
    
    

})

Two, jquery ajax request

After all, jquery ajax is still old. It fell along with jquery. With the rapid rise of front-end frameworks and native js, the dynasty that originally belonged to jquery has been declared dead. Of course, jquery ajax was still very useful in that era. Look at the advantages.
I can only think of one of the advantages, which is more concise than the original syntax, coupled with the simplicity and chain operation of its own operation dom.


// get
$.ajax({
    
    
	method: 'GET'
	url:url,
	success:(data)=>{
    
    
		console.log(data)
	}
});

// post
$.ajax({
    
    
	method: 'POST' 
	url:url,
	data:'yourData',
	success:(data)=>{
    
    
		console.log(data)
	}
})

Three, fetch request

Fetch has become a substitute for Ajax. I don't think so, and fetch is an unencapsulated native request method, which means that developers can encapsulate fetch by themselves without increasing the size of the project. So why can fetch replace ajax?
The advantages are as follows:
1. Concise syntax and more semantic
2. Based on standard Promise implementation, support async/await
3. Convenient isomorphism, using isomorphic-fetch
Next let's look at the method of fetch request, I will attach my own writing later A fetch request

fetch(url,{
    
    
	method:'POST',//'GET'
	mode:'cors',// 跨域请求
	header: new Headers({
    
    
		'Content-Type': 'application/json',
	}),
	body:'yourData'
}).then(data=>{
    
    
	let res = data.json();
	res.then(data=>{
    
    
		console.log(`ok${
      
      data}`)//到此数据就拿到了
	})
})

Four, axios request

The axios request is actually an XMLHttpRequest request, but it is implemented using promise encapsulation. Because all major frameworks are unified to recommend axios to request data, axios has become the mainstream.
The advantages are as follows:
1. Support promise api
2. Prevent from the client CSRF
3. Provide concurrent request API
Next let’s look at the usage of axios

async getUserList(){
    
    	
	let res = await axios.get(url)
}
// 或者
axios.get(url).then(data=>{
    
    
	console.log(data)
})

//当然post也可以这样
async addUser(){
    
    
	let res = await axios.post(url,{
    
    
		data:'yourData'
	})
}
const server_url = "www.baidu.com"

const header = {
    
    
	'content-type':'application-json'
}

const http = {
    
    
	get(url) {
    
    
		return new Promise((resolve, reject) => {
    
    
            fetch(server_url+url,{
    
    
                mode:"cors",
                // credentials:'include',
            }).then(res => {
    
    
                res.json().then(resData => {
    
    
                    resolve(resData);
                })
            }).catch(err => {
    
    
                console.log("err:"+err);
                reject(err);
            })
        })
	},
	post(url,params){
    
    
        return new Promise((resolve,reject)=>{
    
    
            fetch(server_url+url,{
    
    
                headers: header,
                mode: 'cors',
                method: 'POST',
                body: JSON.stringify(params),
            }).then(res => {
    
    
                res.json().then(resData => {
    
    
                    resolve(resData)
                })
            }).catch(err => {
    
    
                console.log("err:"+err);
                reject(err);
            })
        })
    }
}

to sum up

Although there are so many ways to request now, it is still necessary to choose a suitable way according to the project to avoid the project from becoming huge. Of course, there is no need to consider so many things for personal projects. It is good to choose the request method according to your personal habits.

Guess you like

Origin blog.csdn.net/weixin_43889562/article/details/109225952