'use client'; /**前端客户端组件调rest api 接口 */ import { emitAuthExpired } from "@/utils/auth/auth-events"; export async function clientFetch(apiUrl: string | URL, options: RequestInit = {}): Promise { // 请求的是nextjs的代理接口 const headers = { //...(token && { Authorization: `Bearer ${token}` }), "Content-Type": "application/json", }; if(options.headers) { options.headers = Object.assign(headers, options.headers); } else { options.headers = headers; } // fetch 不会reject 非2xx http状态码的响应,而是resolve,所以不会走catch,如果要走catch,需要自己主动抛出异常 const response = await fetch(apiUrl, options); const result = await response.json(); if(response.status === 401) { // Unauthorized 需要登录 emitAuthExpired(); } // if(!response.ok) { // 非2xx状态 // // // } return result; }