getData.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // 封装useFetch
  2. // - composables/useFetchRequest.ts
  3. import { useFetch, useRuntimeConfig } from '#app';
  4. import type { UseFetchOptions } from 'nuxt/app';
  5. interface RequestOptions extends UseFetchOptions<any> {
  6. customBaseURL?: string;
  7. }
  8. type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
  9. type HandleRequestOptions = { request: Request; options: RequestOptions };
  10. type HandleResponseOptions = { response: any };
  11. // 请求拦截器
  12. function handleRequest({ options }: HandleRequestOptions) {
  13. options.headers = {
  14. ...options.headers,
  15. 'Content-Type': 'application/json',
  16. };
  17. }
  18. // 响应拦截器
  19. function handleResponse({ response }: HandleResponseOptions) {
  20. if (response._data.error) {
  21. throw new Error(response._data.error.message || '响应错误');
  22. }
  23. return response._data;
  24. }
  25. /**
  26. * 创建请求方法
  27. * @param method
  28. */
  29. function createUseFetchRequest(method: HttpMethod) {
  30. return async function (
  31. url: string,
  32. data?: any,
  33. options: RequestOptions = {}
  34. ) {
  35. const {
  36. public: {
  37. API_BASE_DEV,
  38. API_BASE_PROD
  39. }
  40. } = useRuntimeConfig();
  41. const baseURL = process.env.NODE_ENV === 'production' ? API_BASE_PROD : API_BASE_DEV;
  42. // console.log(baseURL);
  43. // console.log(process.env.NODE_ENV);
  44. const requestUrl = new URL(
  45. url,
  46. // options.customBaseURL || baseURL
  47. ).toString();
  48. return await useFetch(requestUrl, {
  49. ...options,
  50. method,
  51. body: data,
  52. onRequest: handleRequest,
  53. onResponse: handleResponse
  54. });
  55. };
  56. }
  57. // 提供 useFetch & HTTP 方法 - 统一管理请求 - 再到组件中使用
  58. export const useFetchGet = createUseFetchRequest('GET');
  59. export const useFetchPost = createUseFetchRequest('POST');
  60. export const useFetchPut = createUseFetchRequest('PUT');
  61. export const useFetchDelete = createUseFetchRequest('DELETE');