简体   繁体   中英

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(r.body, {
    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.

From MDN docs :

request.json().then(function(data) {
  // do something with your data
});

This should help you get started:

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

async function handleRequest(request) {
  let requestJSON = await request.json()

  // your logic here

  return await fetch(request, {body: JSON.stringify(requestJSON)})
}

You may want to limit JSON parsing to requests that satisfy the following conditional:

(request.method === "POST" && request.headers.get("Content-Type") === "application/json")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM