CodeBlanks Logo Icon CodeBlanks

HTTP headers

JavaScript course · Intermediate · Lesson 86/134

Learn to build headers and send Accept, Content-Type in requests.

What are headers for?

HTTP headers carry extra information about a request or a response. Through a header you tell the server which response types you accept, the type of the body you are sending, or your credentials.

const headers = new Headers();
headers.set('Accept', 'text/html');

You can write headers as a Headers object or as a plain object. Accept tells which types the client accepts, while Content-Type tells the type of the body being sent. Headers are case insensitive; the casing does not matter.

Adding headers to fetch

To add a header to a fetch call, you pass an options object as the second parameter. The headers property of this object carries the headers.

const response = await fetch(url, {
  headers: { Accept: 'text/html' }
});

The second parameter also takes other options such as method and body. You only write the ones you need. The server looks at these headers and sends the answer in the right type.

Exercise Add a header and read the response type

The url variable holds an address. Make a fetch request with { headers: { Accept: 'text/html' } } as the second parameter and put the response into a response variable. Then log response.headers.get('Content-Type') with console.log.

Show example solution
const response = await fetch(url, {
  headers: { Accept: 'text/html' }
});
console.log(response.headers.get('Content-Type'));

Test yourself

  1. Which header tells the server which type you accept?

    // A
    Content-Type
    // B
    Authorization
    // C
    Accept
    // D
    User-Agent
    • A
    • B
    • C
    • D
    Show answer

    C — Correct! The Accept header lists the types the client accepts.

  2. Match headers to their meanings

    Accept
    Types the client accepts
    Content-Type
    Type of the body being sent
    Authorization
    Credentials
  3. Add the Accept header

    const response = await fetch(url, {
      headers: { ____: 'text/html' }
    });
    Show answer
    const response = await fetch(url, {
      headers: { Accept: 'text/html' }
    });

All lessons in Intermediate