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

如何将客户端数组数据传递到axios POST请求的req.body中

问题根因

参数键多了[]后缀是jQuery AJAX默认的数组参数序列化规则导致的:默认发送application/x-www-form-urlencoded格式请求时,jQuery会自动给数组类型的参数名追加[]标识,后端未适配该规则时就无法直接通过原参数名读取数组值。

解决方案

方案1:前端调整AJAX配置(推荐,无需修改原有后端解构逻辑)

直接修改前端AJAX配置,改为发送JSON格式数据,避免jQuery自动修改参数名:

let notes = []
let reason = []
let values = []
let timestamp = []
$.ajax({
    url: '/postGateway',
    method: 'POST',
    contentType: 'application/json', // 新增:指定请求体格式为JSON
    data: JSON.stringify({ // 修改:将参数对象转为JSON字符串
        analyst: analyst,
        building_number: building_number,
        commodity_tag: commodity_tag,
        meter: meter,
        timestamp: timestamp,
        values: values,
        reason: reason,
        notes: notes
    }),
})

后端确保已开启JSON解析中间件即可(Express框架为例:app.use(express.json())),之后就能直接通过req.body.timestamp读取到数组值。

方案2:后端兼容现有前端传参逻辑

如果不方便修改前端代码,直接调整后端的参数取值逻辑即可:

// 仅解构普通参数,数组参数单独通过带[]的键名读取
const { analyst, building_number, commodity_tag, meter } = req.body
const timestamp = req.body['timestamp[]']
const values = req.body['values[]']
const reason = req.body['reason[]']
const notes = req.body['notes[]']

额外注意事项

你现有后端代码中拼接postdata的逻辑存在问题:已经拿到的timestamp等参数本身就是数组,不需要再额外套一层[],否则会变成二维数组导致第三方接口调用异常,对应逻辑修改为:

const postdata = JSON.stringify({
    'analyst': analyst,
    'building_number': building_number,
    'commodity_tag': commodity_tag,
    'meter': meter,
    'data': {
        'timestamp': timestamp,
        'value': values,
        'reason': reason,
        'notes': notes
    }
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 18:06:06