Debugging Workers API Call

Here is my Workers API function:

export default {
  async fetch(request, env) {
    return new Response(JSON.stringify(request))
  }
}

When I tried to post to it via the Workers API web, I’m getting empty header and "bodyUsed":false:

{"signal":{"aborted":false},"fetcher":{},"redirect":"manual","headers":{},"url":"https://abc.dev.workers.dev/","method":"POST","bodyUsed":false,"body":{"locked":false}}

which I don’t understand at all.

Is there anything I’ve done wrong?

image

You can’t JSON.stringify() the entire request object like that - it’s not all serializable.

If you’re submitting a POST request, you probably want to read the body first, like this:

export default {
	async fetch(request, env) {
		const body = await request.json();
		return Response.json(body); // same as JSON.stringify + JSON content type headers
	}
}

There’s no error handling there and in production you’d probably want to check if it’s a POST request, check for invalid JSON, etc. but it’ll work as long as the JSON you post is valid.

Here’s the full documentation for Request:

Ah, thx. I’ve change it to:

export default {
  async fetch(request, env) {
    if (request.method === "POST") {
      // Getting the POST request JSON payload
      const payload = await request.json()
      return Response.json(payload)
    }
  }
}

However, this is what I’m getting now:

image

Any further way to debug such 500 error pls?

Ops, scrap that. It’s working now.

Maybe I forgot to deploy.

Thanks for your help!!

1 Like

You likely have invalid JSON. You should see the errors in the console when testing in the playground, otherwise I would recommend wrangler for better errors and debugging:

This works for me though:

export default {
	async fetch(request, env) {
		if (request.method === "POST") {
			// Getting the POST request JSON payload
			const payload = await request.json()
			return Response.json(payload)
		}
		return new Response('get');
	}
}

https://cloudflareworkers.com/#c86d09039ed856fb046e83e2b0a6c913:http://about:blank/

Using this payload:

{
	"hello": "world"
}

EDIT: Glad you got it working!!

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.