后台服务:json-server
简单封装axios
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <button onclick="testGet()">GET </button> <button onclick="testPost()">POST </button> <button onclick="testPut()">PUT </button> <button onclick="testDelete()">DELETE </button> <script> function testGet() { axios({ url: 'http://localhost:3000/posts', params: { 'id': 1 } }).then(response => { console.log(response) }, error => { alert(error.message) }) } function testPost() { axios({ url: 'http://localhost:3000/posts', method: 'POST', data: { "id": 2, "title": "json-server3", "author": "typicode" } }).then(response => { console.log(response) }, error => { alert(error.message) }) } function testPut() { axios({ url: 'http://localhost:3000/posts/4', method: 'PUT', data: { "id": 4, "title": "json-server3123", "author": "typicode13" }, }).then(response => { console.log(response) }, error => { alert(error.message) }) } function testDelete() { axios({ url: 'http://localhost:3000/posts/2', method: 'DELETE', }).then(response => { console.log(response) }, error => { alert(error.message) }) } function axios({ url, method = 'GET', params = {}, data = {} }) { return new Promise((resolve, reject) => { //处理method 转为大写 method = method.toUpperCase() //处理query参数(拼接到url上)?id=xx&name=xxx /** { id:xx, name:'' } */ let queryString = ''; Object.keys(params).forEach(key => { queryString += `${key}=${params[key]}&` }) if (queryString) { queryString = queryString.substring(0, queryString.length - 1); url += '?' + queryString } //1.执行异步ajax请求 //创建xhr对象 const request = new XMLHttpRequest() //打开连接(初始化请求,没有开始发送请求) request.open(method, url, true) //发送请求 if (method === 'GET' || method === 'DELETE') { request.send() } else if (method === 'POST' || method === 'PUT') { //发送json格式的数据,必须加上请求头 request.setRequestHeader('Content-Type', 'application/json;charset=utf-8') //告诉请求体格式为json request.send(JSON.stringify(data)) } //绑定状态改变的监听 request.onreadystatechange = function () { if (request.readyState != 4) { //如果请求没有完成,直接结束 return; } //status是200-300之间为成功 const { status, statusText } = request; if (status >= 200 && status <= 299) { //2.1发送成功调用resolve() //准备结果对象response const response = { //request.response是request自己内部封装的json格式的对象,传的是响应体数据 data: JSON.parse(request.response), //响应json数据自动解析为js的对象或数组 status, statusText, }; resolve(response) } else { //2.2发送失败调用reject() reject(new Error('request error status is' + status)) } } }) } </script> </body> </html>