Vectrobyte
Vectrobyte

Reputation: 1485

Parse raw body on cloudflare-worker service(Non NODE)

I've created an api server'ish environment on cloudflare using cloudflare-worker and there is no node server running(cloudflare-worker is pretty much serverless event handler service). It does provide the configurations to handle any subdomain calls much like how api works. I've used a package called cf-worker-router to do so. My cloud service looks like this:

import { ApiError, ApiRedirect, DomainRouter, FetchRouter } from 'cf-worker-router';

const router = new FetchRouter();

// add the cloudflare event listener
addEventListener('fetch', (event) => {
  router.onFetch(event);
});

router.route('/users', 'POST', async (event) => {
  // automatically converts anything not of Response type to ApiResponse
  return await event.request.text();
});

And what I did was create a POST request to the url and supplied some body to the request. I was able to get the request text successfully but now I can't figure out how to parse the text I received.

When using the request as multipart/form-data request and the received body text is as follows:

"----------------------------093590450792211419875705\r\nContent-Disposition: form-data; name=\"name\"\r\n\r\nJon Doe\r\n----------------------------093590450792211419875705--\r\n"

I tried sending application/x-www-form-urlencoded and I the response text as such:

"name=Jon%20Doe"

And Similar for application/json request:

"{\n\t\"name\": \"Jon Doe\"\n}"

Since cloudflare is not using nodejs server, body-parser can't be applied here. This service is pretty much an open api so it needs to take care of all sorts of request content types. Is there any way to identify and decode the strignified contents from any of these content types to a valid object in javascript?

Upvotes: 2

Views: 2285

Answers (1)

Jake Riesterer
Jake Riesterer

Reputation: 116

To handle form data uploads, you can use the request.formData() method which will return a promise of a FormData object.

For example:

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})


async function handleRequest(request) {
  const formData = await request.formData();
  const name = formData.get('name');
  return new Response(`Hello ${name}`);
}

Upvotes: 2

Related Questions