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

Axios POST请求报错:Data after transformation格式异常求助

Axios POST请求报错原因及解决

我使用Axios发送POST请求的代码如下:

const _axios = new Axios({})

await _axios.post(`${ENDPOINT}/raw-houses/should-scrape`, {
  scraper: 'a',
  detail_url: 'b',
  should_not_scrape_reason: 'c'
}, {
  headers: {
    'X-Api-Token': API_TOKEN,
    'Content-Type': 'application/json',
  }
})

执行后出现如下错误:

{
  "code": "ERR_BAD_REQUEST",
  "config": {
    "data": {},
    "headers": {
      "Content-Type": "application/json",
      "User-Agent": "axios/1.4.0",
      "X-Api-Token": "TOKEN"
    },
    "method": "post",
    "url": "http://rentbird.local/api/scrapers/raw-houses/should-scrape"
  },
  "message": "Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",
  "name": "AxiosError",
  "stack": "AxiosError: Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream\n    at dispatchHttpRequest (/Users/dirk/projects/_rentbird/scrapers/node_modules/axios/lib/adapters/http.js:304:23)\n    at /Users/dirk/projects/_rentbird/scrapers/node_modules/axios/lib/adapters/http.js:143:5\n    at new Promise (<anonymous>)\n    at wrapAsync (/Users/dirk/projects/_rentbird/scrapers/node_modules/axios/lib/adapters/http.js:123:10)\n    at http (/Users/dirk/projects/_rentbird/scrapers/node_modules/axios/lib/adapters/http.js:149:10)\n    at Axios.dispatchRequest (/Users/dirk/projects/_rentbird/scrapers/node_modules/axios/lib/core/dispatchRequest.js:51:10)\n    at Axios.request (/Users/dirk/projects/_rentbird/scrapers/node_modules/axios/lib/core/Axios.js:148:33)\n    at Axios.httpMethod [as post] (/Users/dirk/projects/_rentbird/scrapers/node_modules/axios/lib/core/Axios.js:187:19)\n    at Object.setShouldNotScrapeHouse (/Core/ScraperApi.ts:60:22)\n    at WoonmatchWestfriesland.parseHouseBlock (/Scrapers/ScraperInstance.ts:87:30)",
  "status": null
}

该请求在Postman中可正常运行,报错原因及解决办法如下:

报错原因

错误信息显示config.data是空对象,且提示“转换后的数据必须是字符串、ArrayBuffer等类型”,核心问题在于直接使用new Axios({})创建的实例没有默认配置请求转换器(transformRequest)。

Axios的axios.create()方法会自动添加默认转换器,负责将JSON对象序列化为字符串;但直接实例化Axios类时,缺少这个默认配置,导致传入的JSON数据未被正确处理,无法生成符合要求的请求体。Postman会自动完成JSON序列化,因此请求正常。

解决办法

有三种可行方案:

  1. 改用axios.create()创建实例(推荐,符合Axios使用规范)
const _axios = axios.create({}); // 替换new Axios({})
  1. 手动配置transformRequest转换器
    创建Axios实例时添加序列化逻辑:
const _axios = new Axios({
  transformRequest: [(data) => JSON.stringify(data)]
});
  1. 手动将请求数据序列化为JSON字符串
    调用post方法时直接传入字符串格式的请求体:
await _axios.post(`${ENDPOINT}/raw-houses/should-scrape`, JSON.stringify({
  scraper: 'a',
  detail_url: 'b',
  should_not_scrape_reason: 'c'
}), {
  headers: {
    'X-Api-Token': API_TOKEN,
    'Content-Type': 'application/json',
  }
})

内容的提问来源于stack exchange,提问作者Dirk Hoekstra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 02:42:56