1.0.0-beta.1 • Published 1 year ago

@httpland/cors v1.0.0-beta.1

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

cors

deno land deno doc GitHub release (latest by date) codecov GitHub

test NPM

CORS protocol for standard Request and Response.

Packages

The package supports multiple platforms.

  • deno.land/x - https://deno.land/x/cors_protocol/mod.ts
  • npm - @httpland/cors

Treat CORS automatically

withCors accept HTTP request handler and add CORS headers to response header.

import { withCors } from "https://deno.land/x/cors_protocol@$VERSION/mod.ts";
import { Handler, serve } from "https://deno.land/std@$VERSION/http/mod.ts";

function handler(req: Request): Response {
  return new Response("Hello");
}

await serve(withCors(handler));

then, the endpoint support simple request and preflight request.

Utility

We provide utilities based on Living Standard - Fetch, 3.2.2. HTTP requests.

import { isCorsRequest } from "https://deno.land/x/cors_protocol@$VERSION/mod.ts";
import { assertEquals } from "https://deno.land/std@$VERSION/testing/asserts.ts";

assertEquals(isCorsRequest(new Request("http://localhost")), false);
assertEquals(
  isCorsRequest(
    new Request("http://localhost", {
      headers: {
        origin: "http://test.test",
      },
    }),
  ),
  true,
);
import { isCorsPreflightRequest } from "https://deno.land/x/cors_protocol@$VERSION/mod.ts";
import { assertEquals } from "https://deno.land/std@$VERSION/testing/asserts.ts";

assertEquals(isCorsPreflightRequest(new Request("http://localhost")), false);
assertEquals(
  isCorsPreflightRequest(
    new Request("http://localhost", {
      method: "OPTIONS",
      headers: {
        origin: "http://test.test",
        "Access-Control-Request-Method": "POST",
        "Access-Control-Request-Headers": "Content-Type",
      },
    }),
  ),
  true,
);

License

Copyright © 2022-present httpland.

Released under the MIT license