Build Query Strings Safely

So far, the only part of a URL the planner changes is a two-letter country code at the end of the path. Codes like PT and MX are safe to paste into a string because they’re only letters. Values the friends type themselves aren’t always that tidy.

Amara spent her childhood in Trinidad & Tobago and still calls it her other home, so she wants to know whether anyone has saved a weekend there. In this lesson, you’ll send that search to the friends’ trip board, see what happens to the ampersand when you paste the name into a URL, and build URLs so that every value arrives exactly as you typed it. Start with the trip board itself.

Search the Trip Board

The trip board is the stand-in API you planned a POST for in Choose What a Request Needs. Neither real API lets the planner store anything, so the course gives you a small module, tripBoard.mjs, that answers requests to https://trip-board.example/ from inside your program. It parses your URL the way Node.js’s fetch() does, so it sees exactly what a real server would. Nothing goes over the network, and other URLs go to the real fetch().

Before you write the search, open the collapsed block below and copy its code into a file named tripBoard.mjs in your planner folder. You don’t need to read or understand it to follow the course:

Importing this module replaces fetch() with a version that answers the trip board’s address itself:

Language: JavaScript Filename: tripBoard.mjs
// A stand-in for the friends' trip board. It answers
// fetch() calls to https://trip-board.example/ from inside
// your program and passes every other URL to the real
// fetch(). The weekends live in memory, so each run of
// your script starts with an empty board.
const origin = "https://trip-board.example";
const realFetch = globalThis.fetch;
const weekends = [];
const names = {
  PT: "Portugal",
  DE: "Germany",
  JP: "Japan",
  MX: "Mexico",
  TT: "Trinidad & Tobago",
};

function reply(status, body, headers = {}) {
  return new Response(JSON.stringify(body), {
    status,
    headers: {
      "Content-Type": "application/json",
      ...headers,
    },
  });
}

function problem(status, title, detail) {
  return reply(status, { title, status, detail });
}

function matches(weekend, country) {
  const wanted = country.toLowerCase();
  if (!Array.isArray(weekend.countries)) return false;
  return weekend.countries.some(
    (code) =>
      code.toLowerCase() === wanted ||
      names[code]?.toLowerCase() === wanted,
  );
}

async function answer(request) {
  const url = new URL(request.url);
  if (url.pathname !== "/weekends") {
    return problem(404, "Not found", url.pathname);
  }
  if (request.method === "GET") {
    const search = Object.fromEntries(url.searchParams);
    const found =
      search.country === undefined
        ? weekends
        : weekends.filter((weekend) =>
            matches(weekend, search.country),
          );
    return reply(200, { search, weekends: found });
  }
  if (request.method === "POST") {
    const type = request.headers.get("Content-Type");
    const text = await request.text();
    if (!type?.startsWith("application/json")) {
      return problem(
        415,
        "Unsupported Media Type",
        `Expected application/json, got ${type}`,
      );
    }
    let weekend;
    try {
      weekend = JSON.parse(text);
    } catch {
      return problem(
        400,
        "Bad Request",
        `Body isn't JSON: ${text.slice(0, 40)}`,
      );
    }
    const stored = { id: weekends.length + 1, ...weekend };
    weekends.push(stored);
    return reply(201, stored);
  }
  return reply(
    405,
    {
      title: "Method Not Allowed",
      status: 405,
      detail: `${request.method} isn't supported`,
    },
    { Allow: "GET, POST" },
  );
}

globalThis.fetch = async (input, init) => {
  const request = new Request(input, init);
  if (new URL(request.url).origin !== origin) {
    return realFetch(input, init);
  }
  return answer(request);
};

The board’s search takes the country in the query string, as ?country=..., and answers with two things: search, the parameters it read from your URL, and weekends, the saved weekends that match. Nobody has saved a weekend yet, since that’s the next lesson’s job, so the list will be empty. The search part is the one to watch.

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.