Request.headers comes as an empty {} object

Hi,

I am trying to get the request headers in the Workers code, but it prints an empty object --> {}

Code:

addEventListener('fetch', event=>{
    event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
    let responseObject = {
        "headers1": new Map(request.headers),
        "headers2": request.headers
    };
    let responseConfig = {
        "Access-Control-Allow-Origin": "*"
    };
    responseConfig["headers"]["Content-type"] = "application/json";
    return new Response(JSON.stringify(responseObject), responseConfig);
}

The response contains empty “headers1” and “headers2” object.
Note: I just put 2 props to test whether new Map would make any difference.

What am I missing ? why are the headers empty ?

Response:

{
    headers1: {},
    headers2: {}
}

The headers are not empty but stringify won’t work on either of the two types you used.

What you can try instead is to use Object.fromEntries(request.headers).

1 Like

Thanks. Got It.

I used a slightly different approach & that also worked.

let headers = {};
let keys = new Map(request.headers).keys();
let key;
while((key=keys.next().value)){
    headers[key] = request.headers.get(key); 
}
let responseObject = {
    "headers": headers
};
responseConfig["headers"]["Content-type"] = "application/json";
return new Response(JSON.stringify(responseObject), responseConfig);