How to modify request body

I am sending Post request to workers. The post body contents.

{
   "name": "value",
    "name2": "value2"
}

if name2=value2 then I want to modify it:

{
     "name": "value",
     "name2": "NewValue"

}

I am using this script.

addEventListener("fetch", event => {
  event.respondWith(handleRequest(event.request));
});
async function handleRequest(r) {
  return new Response(JSON.parse(r.body).title, {
    headers: {
      "Content-Type": "application/json",
      corsHeaders
    }
  })
}

If I json.parse(r.body) it don’t work. how can I do this? I heard that r.body is a ReadableStream so how to modify it. Please help. Thanks

fetch has a .json method which returns a Promise containing the JSON parsed body Response.json() - Web APIs | MDN

addEventListener("fetch", event => {
  event.respondWith(handleRequest(event.request));
});
async function handleRequest(r) {
  const json = await r.json();

  if (json.name2 === 'value2') {
    json.name2 = 'NewValue';
  }

  return new Response(JSON.stringify(json), {
    headers: {
      "Content-Type": "application/json",
      corsHeaders
    }
  })
}

I haven’t tested this code, there might be a typo somewhere.

1 Like

I am using formData to retrieve those value.
Thanks for the code.