'Pass headers in JSON.stringify
I have a try… catch statement in my code and when there is a catch I want to send a message to me for debugging. Unfortunately I am having a bit of trouble getting headers into the message. Currently I have the following code as the body of my request to the API:
body : `Cloudflare:
${JSON.stringify(request.cf, null, 2)}
Headers:
${JSON.stringify(request.headers)}
Error:
${err}`
The cloudflare and error info comes through perfectly fine, but the headers come out as {} is there any why to fix this?
Thanks!
Edit:
If I remove the JSON.stringify
from the request.headers
I get the output [object Headers]
.
The output currently is:
Cloudflare:
{JSON string with lots data}
Headers:
{}
Error:
ReferenceError:…
Solution 1:[1]
You can do something like this:
const headers = new Headers({
"content-type": "application/json",
"authorization": "Basic <auth>"
});
JSON.stringify(Object.fromEntries([...headers]));
It will print something like this:
{"authorization":"Basic <auth>","content-type":"application/json"}
Solution 2:[2]
JSON.stringify([...request.headers])
Explained here: https://developers.cloudflare.com/workers/examples/logging-headers
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ítalo Sérvio |
Solution 2 | Brett |