原生 Ajax
// get const xhr = new XMLHttpRequest() xhr.open('GET', 'http://luzhaohao.me/common/get?name=zhaohao&age=24') xhr.send() xhr.openreadystagechange = function(){ if(xhr.readystate === XMLHttpRequest.DONE && xhr.status === 200){ console.log(JSON.parse(xhr.responseText)) } } //post const xhr = new XMLHttpRequest() xhr.open('POST', 'http://luzhaohao.me/common/post') xhr.sendRequestHeader('Content-Type', 'application/x-www-form-urlencoded') //'name=luzhaohao&age=24'就是 urlencoded 格式 xhr.send('name=luzhaohao&age=24') xhr.openreadystagechange = function(){ if(xhr.readystate === XMLHttpRequest.DONE && xhr.status === 200){ console.log(JSON.parse(xhr.responseText)) } }
Axios
(async() => { //get const res1 = await axios.get('http://luzhaohao.me/common/get',{ // 可以用对象,也可以像原生一样写 params: { name: 'luzhaohao', age: 24 } }) console.log(res1.data) //post const res2 = await axios.post('http://luzhaohao.me/common/post',{ name: 'luzhaohao', age: 24 }) console.log(res2.data) })()
优化一下⬇️
(async() => { const ins = axios.create({ baseUrl: 'http://luzhaohao.me/common' }) const res1 = await ins.get('/get',{ params: { name: 'luzhaohao', age: 24 } }) console.log(res1.data) const res2 = await ins.post('/post',{ name: 'luzhaohao', age: 24 }) console.log(res2.data) })()
拦截器
(async() => { const ins = axios.create({ baseUrl: 'http://luzhaohao.me/common' }) ins.interceptors.request.use(config ==> { console.log('这是一个拦截器,所有的请求都要经过这里的处理') return config; }) ins.interceptors.response.use(res => { console.log('这是一个拦截器,所有收到的东西都要经过这里的处理') return res; }) const res1 = await ins.get('/get',{ params: { name: 'luzhaohao', age: 24 } }) console.log(res1.data) const res2 = await ins.post('/post',{ name: 'luzhaohao', age: 24 }) console.log(res2.data) })()
Fetch API
//默认是 get, 返回 promise。可以配合 then, async await。 fetch('http://luzhaohao.me/common/get?name=luzhaohao&age=24') .then(res => { if (res.ok) { return res.json() } }) .then(data => { console.log(data) }) //post fetch('http://luzhaohao.me/common/post', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ // {}里是一个 js 对象,除非加上 JSON.stringify(),把 js 对象转成字符串 name: 'luzhaohao', age: 24 }) }) .then(res => { if (res.ok) { return res.json() } }) .then(data => { console.log(data) })
Comments