实现axios

  1. function axios({ method, url, params, data }) {
  2. return new Promise((resolve, reject) => {
  3. method = method.toUpperCase()
  4. //1.创建对象
  5. const xhr = new XMLHttpRequest();
  6. //2.初始化
  7. let str = '';
  8. for (let k in params) {
  9. str += `${k}=${params[k]}&`;
  10. }
  11. if (str) {
  12. url = url + '?' + str.slice(0, -1);
  13. }
  14. xhr.open(method, url);
  15. //3.发送
  16. if (method === 'POST' || method === 'PUT' || method === 'DELETE') {
  17. xhr.setRequestHeader('Content-type', 'application/json;charset=utf-8')
  18. //设置请求体
  19. xhr.send(JSON.stringify(data))
  20. } else {
  21. xhr.send();
  22. }
  23. //4.处理结果
  24. xhr.onreadystatechange = function () {
  25. if (xhr.readyState === 4) {
  26. if (xhr.status >= 200 && xhr.status < 300) {
  27. resolve({
  28. status: xhr.status,
  29. message: xhr.statusText,
  30. body: JSON.parse(xhr.response)
  31. })
  32. } else {
  33. reject(new Error('request error status is ' + xhr.status))
  34. }
  35. }
  36. }
  37. })
  38. }
  39. axios.get = function (url, options) {
  40. return axios(Object.assign(options, { url, method: 'get' }))
  41. }
  42. //post delete put 同
  43. // // 使用形式:
  44. axios({
  45. url: 'https://api.apiopen.top/getJoke',
  46. method: 'GET',
  47. params: {
  48. a: 1,
  49. b: 2
  50. },
  51. data: {
  52. a: 2,
  53. b: 4
  54. }
  55. }).then(
  56. response => {
  57. console.log(response)
  58. }).catch(error => {
  59. console.log(error)
  60. })
  61. // 使用形式:
  62. axios.get('https://api.apiopen.top/getJoke', {
  63. params: {
  64. a: 1,
  65. b: 2
  66. }
  67. }).then(
  68. response => {
  69. console.log(response)
  70. }).catch(error => {
  71. console.log(error)
  72. })

面试官:Vue项目中有封装过axios吗?怎么封装的?