路径参数
简单路径参数
¥Simple path parameter
你可以通过在请求处理程序的路径中包含冒号 :
后跟参数名称来定义路径参数。
¥You can define a path parameter by including a colon :
followed by the parameter name in the path of the request handler.
// 👇 describe parameter types
http.get<{ id: string }>('/posts/:id', () => {})
// 👆 describe parameter position
路径参数表示请求 URL 的动态部分,不会进行逐字匹配。相反,参数位置上存在的任何字符串都将存储在响应解析器参数中公开的 params
对象中。
¥A path parameter represents a dynamic portion of the request URL that won’t be matched literally. Instead, whatever string is present at the parameter’s location will be stored in the params
object exposed in the response resolver argument.
你可以通过响应解析器参数中的 params
对象访问路径参数值。
¥You can access path parameter values through the params
object in the response resolver argument.
http.get<{ id: string }>('/posts/:id', ({ params }) => {
const { id } = params
})
请注意,你可以在同一个请求路径中包含多个不同的路径参数,例如 /users/:userId/books/:bookId
。
¥Note that you can include multiple different path parameters within the same
request path, like /users/:userId/books/:bookId
.
可选路径参数
¥Optional path parameters
使用问号 (?
) 作为路径参数的后缀,表示它是可选的。由于它们的值可能为空,请确保在其类型中反映这一点。
¥Use the question mark (?
) as the suffix of a path parameter to indicate that it’s optional. Since their values are potentially nullable, make sure to reflect that in their types.
http.get<{ id?: string }>('/posts/:id?', ({ params }) => {
const { id } = params
})
使用上述请求处理程序,GET /post
和 GET /post/abc-123
请求都会匹配,但 GET /post/abc-123/edit
不会匹配。
¥With the request handler above, both GET /post
and GET /post/abc-123
requests will match, but GET /post/abc-123/edit
will not.
重复路径参数
¥Repeating path parameter
使用加号 (+
) 作为路径参数的后缀,以指示其值重复。重复的路径参数将在 params
对象中表示为值数组。
¥Use the plus (+
) as the suffix of a path parameter to indicate that its value repeats. Repeating path parameters will be represented as array of values in the params
object.
http.get<{ segments: string[] }>('/settings/:segments+', ({ params }) => {
console.log(params.segments)
})
给定上述请求处理程序,以下是将匹配的路径参数:
¥Given the request handler above, here are the path parameters that will be matched:
请求 URL | params.segments |
---|---|
/settings/user | ["user"] |
/settings/user/privacy | ["user", "privacy"] |
/settings/user/profile/edit | ["user", "profile", "edit"] |
转义分号
¥Escaping semicolon
有时你可能希望在请求路径中包含分号 (;
),但不将其作为参数。使用双反斜杠 (\\
) 来转义此类分号:
¥Sometimes you might want to include a semicolon (;
) in the request path without it becoming a parameter. Use double backslash (\\
) to escape such semicolons:
http.get('/songs/\\:genre/\\:artist', () => {})
类型安全
¥Type safety
MSW 不提供路径参数解析,这意味着所有 params
值要么是字符串,要么是字符串数组。我们强烈建议你在请求处理程序的路径参数类型参数中反映这一点。如果你需要额外的路径参数解析,请手动添加。
¥MSW provides no path parameter parsing, which means that all params
values are either strings or arrays of strings. We strongly encourage to reflect that in the path parameter type argument in your request handlers. If you need additional path parameter parsing, please introduce it manually.