Readme

CORS issues are the bane of frontend engineers.

In Val Town, if you don't customize any CORS headers, we add these defaults:

Access-Control-Allow-Origin: "*"
Access-Control-Allow-Methods: "GET,HEAD,PUT,PATCH,POST,DELETE"

You can override them if you wish to disallow CORS.

This val is a client-side-rendered React app that makes requests to @stevekrouse/cors_example_backend. The backend is in a different val because CORS applies to requests on different domains. The backend has examples of the default permissive CORS behavior and disabled CORS.

Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
2
rozek avatar

currently, your server also adds a Access-Control-Request-Headers header, which is wrong: it should be Access-Control-Allow-Headers

rozek avatar

as mentioned in my bug report, a possible workaround is to handle OPTIONS requests in the val itself, with code similar to the following:

    if (Request.method === 'OPTIONS') {
      return new Response(null, {
        status: 204,
        headers: {
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
          'Access-Control-Allow-Headers': '*'
        },
      })
    }
stevekrouse-cors_example.web.val.run
Updated: December 6, 2024