1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> </style> </head> <body> <script> function Axios (config){ this.config = config } Axios.prototype.request = function (config){ let promise = Promise.resolve(config) let chains = [dispatchRequest, undefined] let result = promise.then(chains[0], chains[1]) return result } function dispatchRequest(config){ return xhrAdapter(config).then(response => { return response },err => { throw err }) } function xhrAdapter (config){ console.log('adapter函数执行了') return new Promise((resolve, reject)=>{ let xhr = new XMLHttpRequest() xhr.open(config.method, config.url) xhr.send() xhr.onreadystatechange = function () { if(xhr.onreadystatechange = 4){ if(xhr.status >= 200 && xhr.status < 300){ resolve({ config: config, data: xhr.response, headers: xhr.getAllResponseHeaders(), request: xhr, status: xhr.status, statusText: xhr.statusText }) }else{ reject(new Error('请求失败' + xhr.status)) } } } }) } let axios = Axios.prototype.request.bind(null) axios({ method: "GET", url:"http://localhost:3000/posts" }).then(response => { console.log(response) }).catch(err => { console.log(err) }) </script> </body> </html>
|