Start learning free

LESSON 5 OF 173 · BACKEND: HOW THE WEB WORKS

Send a Query String in TypeScript

Practice

A query string is the part of a URL after the ?. It carries options for the path as name=value pairs, joined with &. The server reads them and shapes its answer: /prices?max_price=5 asks the supplier for the products that cost 5 or less.

You don't have to write the pairs yourself. Give URLSearchParams an object, and it builds the query string for you. A query string is text, so in TypeScript each value is a string. Join it to the address after a ?. response.url shows the address the request really went to:

const params = new URLSearchParams({ page: "2" });
const response = await fetch(SUPPLIER + "/catalog?" + params);
console.log(response.url);   // http://127.0.0.1:8001/catalog?page=2

The supplier filters its list before it answers, so the products that cost more never leave the server. For /prices with max_price set to 5, your script must print:

URL: http://127.0.0.1:8001/prices?max_price=5
Mug costs 5
Notebook costs 3
Pen costs 1

Your task: create params with new URLSearchParams({ max_price: "5" }), fetch /prices? followed by params, print "URL:" and response.url, then print each product that came back: its name, "costs" and its price.


Assignment
Follow the Coding Tutorial to build the query string with URLSearchParams, print the URL the request went to and print the products the supplier sent back.


Hint
The value is the string "5", not the number. The path ends in a ?: "/prices?", and params comes right after it, joined with +. The answer is an array of products, so read it with await response.json() as Product[] and loop over it with for...of.


STEP 1 OF 6
    Ctrl + Enter to check

    Web Query Params 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