0

I'm trying to send a formData object to a cloudlflare workers function. Here's the original fetch event

const response = await fetch('https://example.workers.dev/createproject', {
    method: 'POST',
    body: formData,
    mode: 'no-cors'
    if (response.ok) {
    ...
    }
    else {
    ...
    }

}

And here is my cloudflare workers index.js file

import { json, missing, ThrowableRouter, withParams } from 'itty-router-extras';
import { createClient } from '@supabase/supabase-js';
const router = ThrowableRouter();
// apiKey is the parsed JWT for a user.
// Not currently supported by Supabase's client, but eventually
// you'll be able to auth _as_ a user by providing this value.
const supabase = (apiKey) => createClient(SUPABASE_URL, SUPABASE_API_KEY);
const parseAuthHeader = (header) => {
    if (!header)
        return;
    const [_, token] = header.split("Bearer ");
    return token;
};

  router.post('/createproject', async ({ request }) => {
    try {
      const formData = await request.formData();
      console.log('success');
      console.log(formData);
    }
    catch (error) {
      console.log('error');
      console.log(error)
    }
    console.log(headers);
    console.log(request);
    return new Response('test');
});
  
  /*
  This is the last route we define, it will match anything that hasn't hit a route we've defined
  above, therefore it's useful as a 404 (and avoids us hitting worker exceptions, so make sure to include it!).
  
  Visit any page that doesn't exist (e.g. /foobar) to see it in action.
  */
  
router.all("*", () => new Response("404, not found!", { status: 404 }))

addEventListener("fetch", event => {
    event.respondWith(router.handle(event.request));
});

In the createproject route, everything that's logged comes back empty (e.g. empty objects, empty arrays) — so it's clearly not accessing the request body or formData object as expected, or I'm not sending the request / formData correctly from the original fetch call.

Can someone help me fix this code so that I can access the request body and formData inside the createproject route?

amatur
  • 317
  • 2
  • 11
  • `Access-Control` headers are **response** headers not **request** headers. Your client-side code can't give itself permission to access other websites. – Quentin Jul 20 '21 at 13:55
  • Hey @Quentin, thanks so much for pointing that out. Even removing all the headers from the fetch call, I still have the same problem. I updated the code accordingly. If you can take another look, that would be much appreciated – amatur Jul 20 '21 at 14:03
  • Well yes. `no-cors` prevents you reading the data and from making preflighted requests. The duplicate question says that. – Quentin Jul 20 '21 at 14:09
  • Just so we're on the same page, as of now, this works as expected: 1. The client initiates the request 2. The request successfully makes it to the cloudflare worker and the `/createproject` route 3. The cloudflare worker successfully handles the request 3. A response is successfully returned to the client This all works when `no-cors` is enabled. The problem arises when the request includes formData. The event listener can log the request, but not the body of the request. When the `createproject` route attempts to log the request, the log output is empty. Is that bc of no-cors? – amatur Jul 20 '21 at 14:46
  • When I remove `no-cors`, I get a cors error on the fetch request. I've also tried using the cors anywhere solution, which also results in a fetch request. And again, using `no-cors`, the fetch request works fine — I'm just struggling to access the data inside the fetch request from the cloudflare worker. So if the problem here is that I'm trying to access request data, in `no-cors` mode, I just wanted to make sure I fully communicated what's going on @Quentin As a different possible opinion, see this from the Cloudflare forum? – amatur Jul 20 '21 at 14:47
  • https://community.cloudflare.com/t/accessing-a-formdata-object-in-a-cloudflare-workers-function/287517/2?u=sbutler ^ That user indicates that, possibly, workers just can't access formData as expected? It's all a bit new to me, so trying to understand what's going on – amatur Jul 20 '21 at 14:50
  • 1
    @Quentin, update: the problem was with the syntax, and the fix included changing the start of the function to `router.post('/createproject', async ( request ) => {`, accessing formData differently in the function, and modifying the original request in the event handler. This fix was independent of the cors setting in the original fetch request from the client. If the thread is unlocked / unmarked as a duplicate, I can share my answer – amatur Jul 20 '21 at 19:52

0 Answers0