代理请求
你可以通过构建代理 Fetch API Request
实例并使用 bypass()
函数执行该实例来代理拦截的请求,以防止其再次匹配相同的请求处理程序。这会将你的 MSW 设置转变为影响本地和外部流量的代理服务器。
¥You can proxy the intercepted request by constructing a proxy Fetch API Request
instance and performing it using the bypass()
function to prevent it from matching the same request handler again. This can turn your MSW setup into a proxy server that affects both local and external traffic.
import { http, bypass } from 'msw'
export const handlers = [
http.get('/resource', async ({ request }) => {
const originalUrl = new URL(request.url)
// Modify the original URL to point to a different server.
originalUrl.hostname = 'api.example.com'
// Construct a proxy request.
const proxyRequest = new Request(proxyUrl, {
headers: {
'content-type': request.headers.get('Content-Type'),
'x-proxy-header': 'abc-123',
},
})
// Perform the proxy request.
const originalResponse = await fetch(bypass(proxyRequest))
// Continue handling the request...
}),
]
bypass
API reference for the `bypass` function.