restApiClient.ts 862 B

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