查询参数

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

要读取被拦截请求的 URL 查询参数,首先从 request.url 字符串中构造一个 URL 实例。URL 实例为你提供了可用于读取查询参数的 URLSearchParams

¥To read the intercepted request’s URL query parameters, first construct a URL instance out of the request.url string. The URL instance provides you with the URLSearchParams that you can use to read the query parameters.

不要将查询参数与请求的路径参数混淆:

¥Do not confuse query parameters with path parameters of the request:

  • 查询参数:?a=1&b=2

    ¥Query parameters: ?a=1&b=2;

  • 路径参数:GET /user/:id,其中 id 是路径参数。

    ¥Path parameters: GET /user/:id, where id is a path parameter.

读取单个参数

¥Read a single parameter

export const handlers = [
  http.get('/product', ({ request }) => {
    // Construct a URL instance out of the intercepted request.
    const url = new URL(request.url)
 
    // Read the "id" URL query parameter using the "URLSearchParams" API.
    // Given "/product?id=1", "productId" will equal "1".
    const productId = url.searchParams.get('id')
 
    // Note that query parameters are potentially undefined.
    // Make sure to account for that in your handlers.
    if (!productId) {
      return new HttpResponse(null, { status: 404 })
    }
 
    return HttpResponse.json({ productId })
  }),
]

读取多值参数

¥Read multi-value parameter

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

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

export const handlers = [
  http.get('/products', ({ request }) => {
    const url = new URL(request.url)
 
    // Given "/products?id=1&id=2&id=3",
    // "productIds" will equal ["1", "2", "3"].
    const productIds = url.searchParams.getAll('id')
 
    return HttpResponse.json({ productIds })
  }),
]

写入查询参数

¥Write query parameters

你在响应解析器中获得的 request 实例代表已经发生的请求。虽然你可以在其查询参数上使用 .set().append() 方法,但这不会对请求产生任何影响。

¥The request instance you get in the response resolver represents a request that has already happened. While you can use the .set() and .append() methods on its query parameters, that will have no effect on the request.

但是,你可以在代理等场景中构建具有修改后的查询参数的新请求。

¥You can, however, construct a new request with modified query paramers in scenarios like proxying.

export const handlers = [
  http.get('/user', ({ request }) => {
    const url = new URL(request.url)
    url.searchParams.set('debug', 'true')
 
    // Construct a proxy request based on the intercepted request
    // but provide a new URL that contains modified query parameters.
    const proxyRequest = new Request(url, request)
  }),
]

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

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

Response patching

Augment original responses