Cloudflare 中文文档
Workers
Workers
编辑这个页面
跳转官方原文档
Set theme to dark (⇧+D)

Logging headers to console

Examine the contents of a Headers object by logging to console with a Map.

​​ Console-logging headers

Use a Map if you need to log a Headers object to the console:

Use the spread operator if you need to quickly stringify a Headers object:

Use Object.fromEntries to convert the headers to an object:

​​ The problem

When debugging Workers, examine the headers on a request or response. A common mistake is to try to log headers to the developer console via code like this:

Or this:

Both attempts result in what appears to be an empty object — the string "{}" — even though calling request.headers.has("Your-Header-Name") might return true. This is the same behavior that browsers implement.

The reason this happens is because Headers objects do not store headers in enumerable JavaScript properties, so the developer console and JSON stringifier do not know how to read the names and values of the headers. It is not actually an empty object, but rather an opaque object.

Headers objects are iterable, which you can take advantage of to develop a couple of quick one-liners for debug-printing headers.

​​ Pass headers through a Map

The first common idiom for making Headers console.log()-friendly is to construct a Map object from the Headers object and log the Map object.

This works because:

  • Map objects can be constructed from iterables, like Headers.

  • The Map object does store its entries in enumerable JavaScript properties, so the developer console can see into it.

​​ Spread headers into an array

The Map approach works for calls to console.log(). If you need to stringify your headers, you will discover that stringifying a Map yields nothing more than [object Map].

Even though a Map stores its data in enumerable properties, those properties are Symbol-keyed. Because of this, JSON.stringify() will ignore Symbol-keyed properties and you will receive an empty {}.

Instead, you can take advantage of the iterability of the Headers object in a new way by applying the spread operator (...) to it.

​​ Convert headers into an object with Object.fromEntries (ES2019)

ES2019 provides Object.fromEntries which is a call to convert the headers into an object:

This results in something like: