查询参数

读取和写入请求查询参数。

读取单个查询参数

¥Read a single query parameter

你可以通过从 request.url 字符串创建 URL 并访问其 searchParams 属性来读取请求的查询参数。

¥You can read the request’s query parameters by creating a URL out of the request.url string and accessing its searchParams property.

http.get('/product', ({ request }) => {
  const url = new URL(request.url)
 
  // Given a request url of "/product?id=1",
  // the `productId` will be a "1" string.
  const productId = url.searchParams.get('id')
 
  if (!productId) {
    return new HttpResponse(null, { status: 404 })
  }
 
  return HttResponse.json({ id: productId })
})

url.searchParamsURLSearchParams 的一个实例,这意味着你可以使用 .get().getAll() 等方法获取查询参数的值。

¥url.searchParams is an instance of URLSearchParams, which means you get the values of query parameters using methods like .get() and .getAll().

读取多值查询参数

¥Read multi-value query parameters

使用 URLSearchParams.prototype.getAll() 方法获取多值查询参数的值列表。

¥Use the URLSearchParams.prototype.getAll() method to get a list of values for multi-value query parameters.

http.get('/products', ({ request }) => {
  const url = new URL(request.url)
 
  // Given a request url of "/products?id=1&id=2&id=3",
  // the `productIds` will be an array of ["1", "2", "3"].
  const productIds = url.searchParams.getAll('id')
})

写入查询参数

¥Write query parameters

虽然 request 对象表示已经发生且无法更改的 Fetch API 请求,但如果你希望将该请求转发到其他地方,仍然可以添加、更改或删除其查询参数。

¥Although the request object represents a Fetch API request that has already happened and cannot be changed, you can still add, change, or remove its query parameters if you wish to forward that request elsewhere.

http.get('/user', ({ request }) => {
  const url = new URL(request.url)
  url.searchParams.set('id', 'another-id')
 
  // Create a proxy request that extends the intercepted request
  // but has modified query parameters in its URL.
  const proxyRequest = new Request(url, request)
})

在此配方中了解有关执行代理请求和修补原始响应的更多信息:

¥Learn more about performing proxy requests and patching the original responses in this recipe:

Response patching

Perform original requests and modify their responses.

类型安全

¥Type safety

查询参数类型始终为 string(单值参数),string[](多值参数)。MSW 不提供任何额外的功能来解析参数值或将其转换为更窄的类型。如果你需要这样的功能,我们建议你自行实现它,并将其作为实用程序函数,以便在你的请求处理程序中复用。

¥Query parameter types are always a string for single parameters and string[] for multi-value ones. MSW provides no additional functionality to parse parameter values or cast them to narrower types. If you ever need such a functionality, we recommend implementing it yourself as a utility function you can reuse across your request handlers.