cors.ts 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { getClientConfig } from "../config/client";
  2. import { ApiPath, DEFAULT_CORS_HOST } from "../constant";
  3. export function corsPath(path: string) {
  4. const baseUrl = getClientConfig()?.isApp ? `${DEFAULT_CORS_HOST}` : "";
  5. if (!path.startsWith("/")) {
  6. path = "/" + path;
  7. }
  8. if (!path.endsWith("/")) {
  9. path += "/";
  10. }
  11. return `${baseUrl}${path}`;
  12. }
  13. export function corsFetch(
  14. url: string,
  15. options: RequestInit & {
  16. proxyUrl?: string;
  17. },
  18. ) {
  19. if (!url.startsWith("http")) {
  20. throw Error("[CORS Fetch] url must starts with http/https");
  21. }
  22. let proxyUrl = options.proxyUrl ?? corsPath(ApiPath.Cors);
  23. if (!proxyUrl.endsWith("/")) {
  24. proxyUrl += "/";
  25. }
  26. url = url.replace("://", "/");
  27. const corsOptions = {
  28. ...options,
  29. method: "POST",
  30. headers: options.method
  31. ? {
  32. ...options.headers,
  33. method: options.method,
  34. }
  35. : options.headers,
  36. };
  37. const corsUrl = proxyUrl + url;
  38. console.info("[CORS] target = ", corsUrl);
  39. return fetch(corsUrl, corsOptions);
  40. }