You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Remix应用配置MSW报错:globalThis.XMLHttpRequest is not a constructor

Remix应用配置MSW时出现XMLHttpRequest构造函数错误的解决方案

我尝试参考示例在Remix应用中配置MSW,但每次都会触发如下错误:

[mf:err] TypeError: globalThis.XMLHttpRequest is not a constructor
at checkTypeSupport (../storefront-remix/node_modules/rollup-plugin-node-polyfills/polyfills/http-lib/capability.js:20:11)
at ../../node_modules/rollup-plugin-node-polyfills/polyfills/http-lib/capability.js (../storefront-remix/node_modules/rollup-plugin-node-polyfills/polyfills/http-lib/capability.js:39:45)
at ../storefront-remix/apps/shop/dist/worker/index.js:14:56
at ../../node_modules/rollup-plugin-node-polyfills/polyfills/http-lib/request.js (../storefront-remix/node_modules/rollup-plugin-node-polyfills/polyfills/http-lib/request.js:1:1)
at ../storefront-remix/apps/shop/dist/worker/index.js:14:56
at node-modules-polyfills:http (../storefront-remix/apps/shop/dist/worker/node-modules-polyfills:http:30:1)
at ../storefront-remix/apps/shop/dist/worker/index.js:14:56
at node-modules-polyfills-commonjs:http (../storefront-remix/apps/shop/dist/worker/node-modules-polyfills-commonjs:http:2:18)
at ../storefront-remix/apps/shop/dist/worker/index.js:17:50
at ../../node_modules/@mswjs/interceptors/lib/interceptors/ClientRequest/index.js (../storefront-remix/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/index.ts:1:1)

当前的MSW配置文件是参考示例修改而来:

import { setupServer } from 'msw/node'
import { handlers } from './msw-handlers'

export function startServer() {
  const server = setupServer(...handlers)
  server.listen({ onUnhandledRequest: 'warn' })
  console.log('MSW initialised')
}

我尝试在app/entry.server.tsx的handleRequest函数开头调用该启动函数:

export default async function handleRequest(
  request: Request,
  responseStatusCode: number,
  responseHeaders: Headers,
  remixContext: EntryContext & { optimizely: OptimizelyLoadContext }
) {
  startServer()

  const markup = renderToString(
    <RemixServer context={remixContext} url={request.url} />
  )

  responseHeaders.set('Content-Type', 'text/html')

  return new Response('<!DOCTYPE html>' + markup, {
    status: responseStatusCode,
    headers: responseHeaders,
  })
}

另外我还试过在/server.ts顶部以及路由文件中调用startServer(路由文件显然不是合适的位置)。

从错误栈来看,问题似乎和MSW内部代码依赖的XMLHttpRequest有关,请问该如何解决这个问题?

内容的提问来源于stack exchange,提问作者Jonathan Tuzman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 21:10:17