Reputation: 69
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.
Upvotes: 1
Views: 4644
Reputation: 76
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")
Upvotes: 2