Leitura e gravação de URL mais seguras em JavaScript moderno

Você pode, sem saber, estar escrevendo URLs de maneira insegura

const url = `https://builder.io/api/v2/content
?model=${model}&locale=${locale}?query.text=${text}`

const res = await fetch(url)

Número 1: Caracteres separadores incorretos

url = url + '?foo=bar'
url = url + '&foo=bar'

Número 2: Esquecer de encodar a URL

const url = `https://builder.io/api/v2/content
?model=${
encodeURIComponent(model)
}&locale=${
encodeURIComponent(locale)
}&query.text=${
encodeURIComponent(text)
}`

Número 3: Caracteres de espaço em branco acidentais

const url = `https://builder.io/api/v2/content`
+ `?model=${
encodeURIComponent(model)
}&locale=${
encodeURIComponent(locale)
}&query.text=${
encodeURIComponent(text)
}`

O construtor URL para o resgate

const url = new URL('https://builder.io/api/v2/content')
url.searchParams.set('model', model)
url.searchParams.set('locale', locale)
url.searchParams.set('text', text)
const res = await fetch(url.toString())

Modificando URLs

url += (url.includes('?') ? '&' : '?') + 'foo=bar'
// Assumindo que `url` é uma URL
url.searchParams.set('foo', 'bar')
// Ou se URL for uma string
const structuredUrl = new URL(url)
structuredUrl.searchParams.set('foo', 'bar')
url = structuredUrl.toString()
const url = new URL('https://builder.io')
url.pathname = '/blog'      // Update the path
url.hash = '#featured' // Update the hash
url.host = 'www.builder.io' // Update the host
url.toString() // https://www.builder.io/blog#featured

Lendo valores de uma URL

const pageParam = new URL(location.href).searchParams.get('page')
const url = new URL(location.href)
const currentPage = Number(url.searchParams.get('page'))
url.searchParams.set('page', String(currentPage + 1))
location.href = url.toString()
const http = require('node:http');

const server = http.createServer((req, res) => {
const url = new URL(req.url, `https://${req.headers.host}`)
// Leia o caminho, query, etc...
});
import { serve } from "https://deno.land/std/http/mod.ts";
async function reqHandler(req: Request) {
const url = new URL(req.url)
// Leia o caminho, query, etc...
return new Response();
}
serve(reqHandler, { port: 8000 });

Propriedades para saber da URL

const url = new URL('https://builder.io/blog?page=1');
url.protocol // https:
url.host // builder.io
url.pathname // /blog
url.search // ?page=1
url.href // https://builder.io/blog?page=1
url.origin // https://builder.io
url.searchParams.get('page') // 1

Métodos URLSearchParams para conhecer

searchParams.has(name)

url.searchParams.has('page') // true

searchParams.get(name)

url.searchParams.get('page') // '1'

searchParams.getAll(name)

url.searchParams.getAll('page') // ['1']

searchParams.set(name, value)

url.searchParams.set('page', '1')

searchParams.append(name, value)

url.searchParams.append('page', '2')

searchParams.delete(name)

url.searchParams.delete('page')

Armadilhas

new URL('/blog') // ERROR!
new URL('/blog', 'https://builder.io')
const params = new URLSearchParams('page=1')
params.set('page=2')
params.toString()
const params = new URLSearchParams({
page: 1,
text: 'foobar',
})
params.set('page=2')
params.toString()

Suporte a navegador e tempo de execução

Créditos

--

--

☕🇳🇿 - https://eduardorabelo.me

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store