User_42
User_42

Reputation: 69

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:…

Upvotes: 0

Views: 3490

Answers (2)

Ítalo Sérvio
Ítalo Sérvio

Reputation: 303

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"}

Upvotes: 5

Brett
Brett

Reputation: 848

JSON.stringify([...request.headers])

Explained here: https://developers.cloudflare.com/workers/examples/logging-headers

Upvotes: 2

Related Questions