我正在为我的 React 应用程序使用 MSW,并且在尝试以模拟模式运行时出现以下错误;尝试将请求 /api/myApi 从 localhost:3000 代理到 { port: 8080 } (ECONNREFUSED) ( https://nodejs.org/api/errors.html#errors_common_system_errors ) 时发生错误我正在尝试将两者用于测试和作为开发 api 服务器(模拟数据)
不确定在模拟模式下运行时代理请求是否需要额外的配置。
下面是我在 package.json 中的命令
"start:mock": "cross-env NODE_ENV=mock webpack serve --progress --config config/webpack.local.js",
下面是 src/index.js 中的代码
import * as serviceWorker from './serviceWorker';
if (process.env.NODE_ENV === 'mock') {
const { worker } = require('./browser')
worker.start()
}
//src/browser.js
import { setupWorker } from 'msw'
import { handlers } from './testServer'
// This configures a Service Worker with the given request handlers.
export const worker = setupWorker(...handlers)
下面是 src/testServer.js
import "whatwg-fetch";
import { rest } from "msw";
import { setupServer } from "msw/node";
import data from "./data";
const handlers = [
rest.get("http://localhost/api/myApi", (req, res, ctx) => {
return res(ctx.status(200), ctx.json(data));
})
];
// This configures a request mocking server with the given request handlers.
const server = setupServer(...handlers);
beforeAll(() => server.listen());
afterAll(() => server.close());
afterEach(() => server.resetHandlers());
export { server, rest, handlers};