Start learning free

LESSON 6 OF 173 · BACKEND: HOW THE WEB WORKS

Headers in TypeScript

Practice

A response is more than its body. Before the body come the headers: lines of Name: value about the body, like the writing on an envelope around a letter. In TypeScript, response.headers holds them, and its get method takes a header's name and gives back its value: a string, or null when the header is missing. The header Content-Type says what kind of body this is: text/html for a web page, application/json for JSON.

Requests carry headers too, and you can add your own. Build the request first with new Request: the address, then an object whose headers key holds an object of them. Then hand the request to fetch. The Accept header tells the server which kind of answer you want. After the call, request.headers are the headers your request carried. For example, to send an Accept-Language header that asks for French, and check that it went out:

const request = new Request(SUPPLIER + "/catalog", { headers: { "Accept-Language": "fr" } });
const reply = await fetch(request);
console.log(request.headers.get("Accept-Language"));

When you set no Accept of your own, fetch sends Accept: */*, which means anything will do. Your script asks for two paths and prints what their headers say:

GET /                                    →  Content-Type: text/html; charset=utf-8
GET /prices  (Accept: application/json)  →  Content-Type: application/json; charset=utf-8
Body: Supplier API. Try /prices
Content-Type: text/html; charset=utf-8
Sent Accept: application/json
Got Content-Type: application/json; charset=utf-8

Your task: the starting code asks for the home page and prints its body. Print its Content-Type. Then ask for /prices with an Accept header for JSON, and print the Accept header that went out and the Content-Type that came back.


Assignment
Follow the Coding Tutorial to read the Content-Type of two answers and send an Accept header of your own.


Hint
response.headers are the headers that came back; request.headers are the ones that went out. Read both with .get and the header's name in quotes. response was declared with let, so store the new answer in it without declaring it again.


STEP 1 OF 5
    Ctrl + Enter to check

    Web Headers in TypeScript

    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free