restApiClient.ts 981 B

1234567891011121314151617181920212223242526272829
  1. 'use client';
  2. /**前端客户端组件调rest api 接口 */
  3. import { emitAuthExpired } from "@/utils/auth/auth-events";
  4. export async function clientFetch<T = any>(apiUrl: string | URL, options: RequestInit = {}): Promise<T> {
  5. // 请求的是nextjs的代理接口
  6. const headers = {
  7. //...(token && { Authorization: `Bearer ${token}` }),
  8. "Content-Type": "application/json",
  9. };
  10. if(options.headers) {
  11. options.headers = Object.assign(headers, options.headers);
  12. } else {
  13. options.headers = headers;
  14. }
  15. // fetch 不会reject 非2xx http状态码的响应,而是resolve,所以不会走catch,如果要走catch,需要自己主动抛出异常
  16. const response = await fetch(apiUrl, options);
  17. const result = await response.json();
  18. if(response.status === 401) { // Unauthorized 需要登录
  19. emitAuthExpired();
  20. }
  21. // if(!response.ok) { // 非2xx状态
  22. // //
  23. // }
  24. return result;
  25. }