Skip to main content
基本 Svelte
介绍
反应性
属性
逻辑
事件
绑定
类和样式
动作
转换
高级 Svelte
高级反应性
重用内容
运动
高级绑定
高级转换
上下文 API
特殊元素
<script module>
后续步骤
基本 SvelteKit
介绍
路由
加载数据
标题和 cookie
共享模块
表单
API 路由
$app/state
错误和重定向
高级 SvelteKit
钩子
页面选项
链接选项
高级路由
高级加载
环境变量
结论

要防止路由匹配无效输入,你可以指定匹配器。例如,你可能希望像 /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:

src/params/hex
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.

上一页 下一页
1
2
<h1>color picker</h1>