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

MSW Server POST请求未返回响应体问题排查

问题:MSW模拟400响应时Axios返回data为空字符串

我在配置MSW Server时编写了如下代码:

const server = setupServer(
    http.post('http://172.17.0.1:3001/auth/confirm', async ({ request }) => {
        const newPost = await request.json() as Request;

        return HttpResponse.json({ body: newPost }, { status: 400 });
    })
);

测试环境初始化代码:

beforeAll(() => server.listen());
render(<ConfirmationPage />);

组件加载时通过Axios发送请求:

axios.post('http://172.17.0.1:3001/auth/confirm', {
    headers: { 'Content-Type': 'application/json' }, responseType: 'json'
}).then(response => {
    console.log('here success', response);
}).catch(error => {
    console.log('here error', error);
});

但响应返回的data为空字符串:

{ data: '', status: 400 ...}

额外环境信息:Jest的testEnvironment为jest-environment-jsdom,setupFiles配置如下:

const { TextDecoder, TextEncoder } = require('util');
const { Response } = require('whatwg-fetch');

global.Response = Response;

global.TextEncoder = TextEncoder;
global.TextDecoder = TextDecoder;

请问为何响应体为空,该如何解决?


原因分析

  1. Axios请求参数传递错误:axios.post的第二个参数应为请求体数据,第三个参数才是配置对象。你将配置放在第二个参数位置,导致请求体格式异常,MSW解析request.json()可能失败,进而影响响应生成。
  2. 全局Response冲突:手动在setupFiles中挂载whatwg-fetch的Response到全局,会与MSW内部依赖的标准Fetch API实现冲突,导致响应体序列化失败,Axios无法解析出有效data。
  3. 错误响应的解析逻辑:Axios在处理4xx/5xx状态码时会进入catch块,若响应体无法被正确序列化,会返回空字符串作为data。

解决方案

1. 修正Axios请求参数格式

调整axios.post的参数顺序,将请求体和配置分开传递:

axios.post(
  'http://172.17.0.1:3001/auth/confirm',
  // 传入实际请求体数据,若无数据可传空对象{}
  {},
  {
    headers: { 'Content-Type': 'application/json' },
    responseType: 'json'
  }
).then(response => {
    console.log('here success', response);
}).catch(error => {
    // 错误时需访问error.response获取响应详情
    console.log('here error', error.response);
});

2. 移除全局替换的Response

jsdom环境已内置Fetch API实现,无需手动挂载whatwg-fetch的Response,删除setupFiles中的相关代码:

const { TextDecoder, TextEncoder } = require('util');

global.TextEncoder = TextEncoder;
global.TextDecoder = TextDecoder;

3. 确保MSW响应的有效性(可选)

若上述步骤后仍有问题,可显式指定响应的Content-Type头,或捕获请求体解析错误:

const server = setupServer(
    http.post('http://172.17.0.1:3001/auth/confirm', async ({ request }) => {
        try {
            const newPost = await request.json() as Request;
            return HttpResponse.json({ body: newPost }, { 
                status: 400,
                headers: { 'Content-Type': 'application/json' }
            });
        } catch (err) {
            return HttpResponse.json({ error: 'Invalid request body' }, { status: 400 });
        }
    })
);

内容的提问来源于stack exchange,提问作者Cai Allin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 05:25:26