cors.ts 760 B

123456789101112131415161718192021222324252627282930313233343536
  1. import { ApiPath } from "../constant";
  2. import { getApiPath } from "./path";
  3. export function corsFetch(
  4. url: string,
  5. options: RequestInit & {
  6. proxyUrl?: string;
  7. },
  8. ) {
  9. if (!url.startsWith("http")) {
  10. throw Error("[CORS Fetch] url must starts with http/https");
  11. }
  12. let proxyUrl = options.proxyUrl ?? getApiPath(ApiPath.Cors);
  13. if (!proxyUrl.endsWith("/")) {
  14. proxyUrl += "/";
  15. }
  16. url = url.replace("://", "/");
  17. const corsOptions = {
  18. ...options,
  19. method: "POST",
  20. headers: options.method
  21. ? {
  22. ...options.headers,
  23. method: options.method,
  24. }
  25. : options.headers,
  26. };
  27. const corsUrl = proxyUrl + url;
  28. console.info("[CORS] target = ", corsUrl);
  29. return fetch(corsUrl, corsOptions);
  30. }