使用axios.post返回的Response缺少status和statusText字段的原因
问题描述
使用Axios发起POST请求的代码如下:
try { const postResponse: any = await axios.post( url, messageBody, { headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'Authorization': `Bearer ${token}` } } ); logger.info('Response:', {postResponse: postResponse, ...logExt}); return postResponse; } catch(err: any){ <catch block code here> }
日志输出的postResponse包含config、data、headers、request字段,但缺少官方文档定义的status和statusText字段,同时存在循环引用。
Axios官方定义的响应Schema如下:
{ // `data` is the response that was provided by the server data: {}, // `status` is the HTTP status code from the server response status: 200, // `statusText` is the HTTP status message from the server response // As of HTTP/2 status text is blank or unsupported. // (HTTP/2 RFC: https://www.rfc-editor.org/rfc/rfc7540#section-8.1.2.4) statusText: 'OK', // `headers` the HTTP headers that the server responded with // All header names are lower cased and can be accessed using the bracket notation. // Example: `response.headers['content-type']` headers: {}, // `config` is the config that was provided to `axios` for the request config: {}, // `request` is the request that generated this response // It is the last ClientRequest instance in node.js (in redirects) // and an XMLHttpRequest instance in the browser request: {} }
请问为何返回的对象与官方Schema相比缺少这两个字段?
可能的原因及解决思路
日志序列化截断字段:多数日志库在处理含循环引用的对象时,会为避免报错截断内容,甚至跳过部分可枚举属性。Axios的
status和statusText本身是可枚举的,但如果序列化工具(如部分JSON库)无法处理config与request间的循环引用,就可能在截断时丢失这两个字段。可以直接打印postResponse.status和postResponse.statusText验证是否存在,而非序列化整个响应对象。Axios版本兼容问题:不同版本的Axios响应结构可能存在差异,旧版本可能在特定场景下未正确填充
status和statusText。检查当前Axios版本,升级至最新稳定版后重试。响应拦截器修改返回值:若项目配置了全局Axios响应拦截器,可能存在仅返回
response.data的逻辑,导致外层的status和statusText被丢弃。检查拦截器代码,确认是否有类似return response.data的操作。HTTP/2协议限制:根据官方注释,HTTP/2协议下
statusText可能为空或不被支持,但status字段仍应存在。若请求通过HTTP/2发送,可确认服务器使用的协议版本,排查statusText为空的情况。
内容的提问来源于stack exchange,提问作者Devesh Soni

