Ember应用中Mirage配置passthrough返回空Response而非接口JSON数据
Ember开发接入Mirage后的Passthrough空响应问题记录
初始异常
应用启动后首次向http://localhost:3006/data.json发起GET请求时,控制台抛出Mirage路由缺失错误:
Mirage: Your Ember app tried to GET 'http://localhost:3006/data.json', but there was no route defined to handle this request. Define a route that matches this path in your mirage/config.js file. Did you forget to add your namespace?
初步处理操作
按照Mirage官方文档说明,在mirage/config.js配置文件中添加了passthrough规则,让目标请求绕过Mirage拦截:
this.passthrough('http://localhost:3006/data.json');
配置完成后,控制台的路由缺失报错不再出现,但请求的实际返回结果不符合预期。
业务侧发起的请求代码为:
fetch(`${host}/data.json`) .then(res => res.json()) .then(data => { // 对返回的data执行业务逻辑 });
异常响应表现
配置生效后,实际拿到的Response对象状态为正常200,但响应体为空,具体结构如下:
{ bodyUsed: true, headers: Headers {map: {…}}, ok: true, status: 200, statusText: "OK", type: "default", url: "http://localhost:3006/data.json", _bodyInit: null, _bodyText: "" }
而业务预期获取的JSON响应结构为:
{ "files": { "x": "any", "a": "any", "b": "any", "c": "any" } }
调试定位结论
在Pretender.js源码中打断点逐行排查,发现Mirage底层依赖的Pretender生成的FakeRequest对象存在属性异常:
responseType为空字符串response属性值为null- 仅
responseText属性存有目标接口返回的有效响应内容
追踪Pretender内部的响应取值逻辑可以发现,代码的判断优先级为:只要当前xhr对象上存在response属性,就优先读取该属性的值;只有当response属性不存在时,才会兜底读取responseText的内容。由于当前FakeRequest对象上存在值为null的response属性,直接命中了空响应返回分支,没有进入读取有效responseText的逻辑,最终导致业务侧拿到了空响应。
内容的提问来源于stack exchange,提问作者Shreya Shah
相关产品推荐
相关产品推荐

