-2

I am experimenting a things that I don't understand. When I try to set headers of a request using the Fetch API, no headers are actually defined.

Here is a piece of code and a link to a fiddle to be able to reproduce.

function createRequest(type, url, payload) { const options = { headers: { "Content-Type": "application/json", "x-request-id": '...', "x-sender-id": "mysender" }, method: 'POST', body: JSON.stringify(payload), mode: 'no-cors', cache: 'no-cache' }; return new Request(url, options); } // ----------------------------- // a simple test const request = createRequest('post', '/check', {test: 'where are my headers?'}); 

When I create the headers using the Headers object, headers are dropped out. This is the case even if I am using the set or append method to fill headers. Using new Headers({...}); as it is stated here does not solve the issue. Changing the mode also produces no change. Folowing this also fails.

Link to the fiddle

As a result, no headers (and no body I guess) are defined.

enter image description here

enter image description here

If somebody has an idea about the issue, I'll take it :D

Regards.

0

1 Answer 1

1

Since you are using mode: 'no-cors' you are restricted to simple headers

  • accept
  • accept-language
  • content-language
  • content-type

That's all the headers you are allowed in no-cors mode

source: documentation

below, the first request is made mode no-cors and the second mode same-origin (though, this could also be cors and would work the same)

// Code goes here function createRequest(type, url, payload, corsmode) { const options = { headers: { "Content-Type": "application/json", "x-request-id": '...', "x-sender-id": "mysender" }, method: 'POST', body: JSON.stringify(payload), mode: corsmode, cache: 'no-cache' }; return new Request(url, options); } // ----------------------------- // a simple test const request = createRequest('post', '/check', { test: 'where are my headers?' }, 'no-cors'); console.log([...request.headers.entries()]); const request2 = createRequest('post', '/check', { test: 'where are my headers?' }, 'same-origin'); console.log([...request2.headers.entries()]);

Sign up to request clarification or add additional context in comments.

1 Comment

@ollie314 - I've added a code snippet to show the difference and to show how you can log the headers to the console

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.