Hi, I’m working on a project that will use workers to inspect the POST body of a request and then forward that post body to the origin after the inspection as a new request. I’ve followed the advice from a post with a similar situation as mine:
https://community.cloudflare.com/t/getting-post-parameters-via-request-formdata-prevents-forwarding-the-original-request/15349/3
I’ve had this functionality work before, but when I tried it again I seem to be getting the following error, with the request body not being forwarded to the origin in my new request.
error!: SyntaxError: Unexpected token < in JSON at position 0
I’m not really sure how to debug this as I’m not sending any JSON at all…
Here is some example code that can be used to reproduce the issue:
// Event Listenter for each request
addEventListener('fetch', event => {
event.respondWith(fetchAndApply(event.request))
});
// Intercept, and analyze the request
async function fetchAndApply(request) {
// Process POST request
if(request.method == 'POST'){
try {
let body = await request.text();
let formData = new URLSearchParams(body);
// forward the request to the origin server with the submitted POST data and append an extra header
let newRequest = new Request(request, { body })
newRequest.headers.set('X-testing', 1);
return await fetch(newRequest);
} catch (err) {
return new Response(`error!: ${err}`, {status: 500}); // return 500 Status with Error
}
}
return fetch(request);
};
Any ideas? Thanks!
You need to pass the POST as below, repeat the request
fetch(request,request)
Thanks for this, but I’m not sure that this is related to how I’m giving fetch the POST body. Even if I try to reconstruct the request and send it manually I receive the same error, only intermittently. I’ve gotten this to work, but then it stops working after I deploy the worker code with this error:
error!: SyntaxError: Unexpected token < in JSON at position 0
Here’s the new example code that I’m using to reproduce this error:
// Event Listenter for each request
addEventListener('fetch', event => {
event.respondWith(fetchAndApply(event.request))
});
// Intercept, and analyze the request
async function fetchAndApply(request) {
// Process POST request
if(request.method == 'POST'){
try {
// forward the request to the origin server with the submitted POST data and append an extra header
let content = await request.text();
let headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'X-Testing': 1
}
const init = {
method: 'POST',
headers: headers,
body: content
}
const response = await fetch(decodeURIComponent(request.url.toLowerCase()), init);
console.log('Got response', response);
return response;
return response
} catch (err) {
return new Response(`error!: ${err}`, {status: 500}); // return 500 Status with Error
}
}
return fetch(request);
};
Further more here’s a screenshot of the error I am receiving after submitting form data.
Are you able to reproduce this error? Thanks