要防止路由匹配无效输入,你可以指定匹配器。例如,你可能希望像 /colors/[value]
这样的路由匹配十六进制值(如 /colors/ff3e00
),但不匹配命名颜色(如 /colors/octarine
)或任何其他任意输入。
¥To prevent the router from matching on invalid input, you can specify a matcher. For example, you might want a route like /colors/[value]
to match hex values like /colors/ff3e00
but not named colors like /colors/octarine
or any other arbitrary input.
首先,创建一个名为 src/params/hex.js
的新文件并从中导出一个 match
函数:
¥First, create a new file called src/params/hex.js
and export a match
function from it:
export function match(value) {
return /^[0-9a-f]{6}$/.test(value);
}
然后,要使用新的匹配器,请将 src/routes/colors/[color]
重命名为 src/routes/colors/[color=hex]
。
¥Then, to use the new matcher, rename src/routes/colors/[color]
to src/routes/colors/[color=hex]
.
现在,每当有人导航到该路由时,SvelteKit 都会验证 color
是否为有效的 hex
值。如果没有,SvelteKit 将尝试匹配其他路由,最终返回 404。
¥Now, whenever someone navigates to that route, SvelteKit will verify that color
is a valid hex
value. If not, SvelteKit will try to match other routes, before eventually returning a 404.
匹配器在服务器和浏览器中运行。
¥[!NOTE] Matchers run both on the server and in the browser.
<h1>color picker</h1>