kwhitley/itty.dev

CORS not working with IttyRouter

Closed this issue · 2 comments

Is CORS only supported by AutoRouter and Router?

Minimal code:

import { IttyRouter, cors, error, json } from 'itty-router';

// Create CORS handlers
const { preflight, corsify } = cors();

// Create a new router
const router = IttyRouter();

// Handle CORS preflight requests
router.options('*', preflight);

// Define root route
router.get('/', () => ({ ok: true }));

export default {
  fetch: (request, ...args) =>
    router
      .fetch(request, ...args)
      .then(json)   // Downstream formatting for non-Responses
      .catch(error) // Error handling
      .finally((r) => corsify(r, request))
};

Error from Cloudflare log: "Cannot read properties of undefined (reading 'body')"

Looks like the issue is with .finally(), which doesn't receive the Promise response - needs to be .then() which does!

import { IttyRouter, cors, error, json } from 'itty-router';

// Create CORS handlers
const { preflight, corsify } = cors();

// Create a new router
const router = IttyRouter();

// Handle CORS preflight requests
router.options('*', preflight);

// Define root route
router.get('/', () => ({ ok: true }));

export default {
  fetch: (request, ...args) =>
    router
      .fetch(request, ...args)
      .then(json)   // Downstream formatting for non-Responses
      .catch(error) // Error handling
      .then((r) => corsify(r, request)) // <-- should be a `.then()` to actually get the response
};

That fixed it -- thanks for the quick response!

I'll close this, but you may want to update the instructions :-).