1. // 引入axios包
    2. import axios from 'axios'
    3. // POST 方法封装 (参数处理)
    4. export const postRequest = (url, params) => {
    5. return axios({
    6. method: 'post',
    7. url: url,
    8. data: params,
    9. transformRequest: [function(data) {
    10. let result = ''
    11. for(let item in data) {
    12. result += encodeURIComponent(item) + '=' + encodeURIComponent(data[item]) + '&'
    13. }
    14. return result
    15. }],
    16. headers: {
    17. 'Content-Type': 'application/x-www-form-urlencoded'
    18. }
    19. });
    20. }
    21. // POST 方法封装 (文件上传)
    22. export const uploadFileRequest = (url, params) => {
    23. return axios({
    24. method: 'post',
    25. url: url,
    26. data: params,
    27. headers: {
    28. 'Content-Type': 'multipart/form-data'
    29. }
    30. });
    31. }
    32. // GET 方法封装
    33. export const getRequest = (url) => {
    34. return axios({
    35. method: 'get',
    36. url: url
    37. });
    38. }
    39. // PUT 方法封装
    40. export const putRequest = (url, params) => {
    41. return axios({
    42. method: 'put',
    43. url: url,
    44. data: params,
    45. transformRequest: [function(data) {
    46. let ret = ''
    47. for(let it in data) {
    48. ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
    49. }
    50. return ret
    51. }],
    52. headers: {
    53. 'Content-Type': 'application/x-www-form-urlencoded'
    54. }
    55. });
    56. }
    57. // DELETE 方法封装
    58. export const deleteRequest = (url) => {
    59. return axios({
    60. method: 'delete',
    61. url: url
    62. });
    63. }
    64. // 在main.js中引入
    65. import {getRequest, postRequest, deleteRequest, putRequest} from '@/utils/request.js'
    66. // 将axios RESTful请求封装方法添加到VUE原型上
    67. Vue.prototype.getRequest = getRequest;
    68. Vue.prototype.postRequest = postRequest;
    69. Vue.prototype.deleteRequest = deleteRequest;
    70. Vue.prototype.putRequest = putRequest;