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 es through perfectly fine, but the headers e 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:…
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 es through perfectly fine, but the headers e 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:…
Share
Improve this question
edited Dec 28, 2021 at 11:41
User_42
asked Dec 28, 2021 at 11:00
User_42User_42
691 silver badge7 bronze badges
7
- 1 I dont understand what you are trying to do. What body is this? Why don't you stringify the full object but mix it with sting iterpolation? – The Fool Commented Dec 28, 2021 at 11:11
-
1
Well, what kind of object exactly is
request
andrequest.headers
…? – deceze ♦ Commented Dec 28, 2021 at 11:37 - The body is for an API request, and the string interpolation is being used, but I cannot get the data out of the headers variable. – User_42 Commented Dec 28, 2021 at 11:37
-
It would help if you edit the question to include the exact string that is generated after the
body :
property name. And also what it needs to be. Also tryconsole.table(request.headers)
and show that to us. – Peter B Commented Dec 28, 2021 at 11:40 -
request
is a variable with info about the request, andrequest.headers
includes the headers. If Iconsole.log(request.headers)
then I get: HeadersList(44) [ 'accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8', … ] – User_42 Commented Dec 28, 2021 at 11:46
2 Answers
Reset to default 5You 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"}
JSON.stringify([...request.headers])
Explained here: https://developers.cloudflare./workers/examples/logging-headers