Using GET with parameters
suggest changeIn a browser page, use URL and URLSearchParams to encode query parameters, then request them with fetch(). The call below uses top-level await, which belongs in a module:
async function getText(path, params, { signal } = {}) {
const url = new URL(path, window.location.href);
url.search = new URLSearchParams(params);
const response = await fetch(url, { signal });
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.text();
}
try {
const responseText = await getText('/cars.php', {
type: 'Volvo',
model: '300',
color: 'purple',
});
console.log(responseText);
} catch (error) {
console.error(error);
}
URLSearchParams handles escaping delimiters, spaces, and non-ASCII text. Repeated keys can be added with its append() method when an endpoint expects several values for one parameter.
The server must still validate and normalize every parameter; URL encoding is not input validation.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents