bypass

在拦截算法之外执行额外请求。

调用签名

¥Call signature

globalThis.fetch() 函数一样,bypass 函数需要两个参数:RequestInputRequestInit。它返回一个修改后的输入和初始化参数的元组,然后在常规 globalThis.fetch() 调用中提供。

¥The same as the globalThis.fetch() function, the bypass function expects two arguments: RequestInput and RequestInit. It returns a tuple of modified input and init arguments to then be provided on the regular globalThis.fetch() call.

function bypass(input: RequestInput, init?: RequestInit): Request {}

bypass.ts

Source code for the `bypass` namespace.

用法

¥Usage

此方法旨在在库的拦截算法之外执行 HTTP 请求。通过 bypass() 执行的请求永远不会被拦截,即使网络描述中存在匹配的请求处理程序。这种特殊​​行为支持更复杂的网络场景,例如 响应修补

¥This method is designed to perform HTTP requests outside of the library’s interception algorithm. Requests performed via bypass() will never be intercepted, even if there are otherwise matching request handlers present in the network description. This special behavior enables more complex network scenarios, such as Response patching:

import { http, bypass, HttpResponse } from 'msw'
 
export const handlers = [
  http.get('/user', async ({ request }) => {
    // Perform the intercepted "GET /user" request as-is
    // by passing its "request" reference to the "bypass" function.
    const response = await fetch(bypass(request))
    const realUser = await response.json()
 
    // Return a mocked JSON response by patching the original response
    // together with a mocked data.
    return HttpResponse.json({
      ...realUser,
      lastName: 'Maverick',
    })
  }),
]

passthrough() 不同,bypass() 函数会导致发出额外的请求。你可以将其视为在处理请求时请求额外资源的服务器。因此,如果你只想按原样执行拦截的请求(在这种情况下使用 passthrough()),则不得使用 bypass()

¥Unlike passthrough(), the bypass() function results in an additional request being made. You can think of it as a server requesting additional resources while handling a request. Because of this, bypass() must not be used when all you wish is to perform the intercepted request as-is (use passthrough() in that case).

相关材料

¥Related materials