[英]How to pass an array of data from the client side to req.body of an axios post request
我正在尝试使用 ajax 调用将在我的前端收集的用户数据发送到我在后端设置的 axios 发布请求。 我有一些参数需要发回一组数据。 当我在后端 console.log(req.body) 时,数据与我设置为 req.body 的变量匹配,除了应该在数组中接受的变量,它们是时间戳、值、原因,笔记。
postModel: async (req, res) => {
const { analyst, building_number, commodity_tag, meter, timestamp, values, reason, notes } = req.body
console.log(req.body)
try {
const headers = {
'Content-Type': 'application/json',
'authorizationToken': token.token
}
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]
}
})
const postModel = process.env.POST_API_URL
const response = await axios.post(postModel, postdata, {
headers: headers
})
return res.json(response.data)
} catch (error) {
console.error(error.message)
return res.json(error)
}
这是使用前端 ajax 调用发送回数据后记录到控制台的 req.body。 应该是 arrays 的四个变量以奇怪的字符串格式返回,当我尝试使用该变量时,值是 null 所以没有任何东西传递给 Z38C3787939C7B0B6C77D73FCE3D28891 数据。 或者例如,如果我尝试 console.log(timestamp) 它返回为未定义,但如果我 console.log(meter) 它给了我正确的值。 如何阻止数组数据以字符串格式发送到我的后端并将其放入我的 req.body 变量中,以便我可以在 axios 发布数据中使用它?
[Object: null prototype] {
analyst: 'email@email.com',
building_number: '0227',
commodity_tag: 'S',
meter: '2032',
'timestamp[]': [ '2021-10-05', '2021-10-06', '2021-10-07', '2021-10-08' ],
'values[]': [ '5830', '6119', '5830', '5830' ],
'reason[]': [ 'Investigate', 'Investigate', 'Investigate', 'Investigate' ],
'notes[]': [
'Testing backend',
'Testing backend',
'Testing backend',
'Testing backend'
]
}
这是前端 ajax 调用。 我将数据推送到四个空的 arrays 中,然后在下面的数据值中设置这些变量。
let notes = []
let reason = []
let values = []
let timestamp = []
$.ajax({
url: '/postGateway',
method: 'POST',
data: {
analyst: analyst,
building_number: building_number,
commodity_tag: commodity_tag,
meter: meter,
timestamp: timestamp,
values: values,
reason: reason,
notes: notes
},
})
弄清楚了。 我只需要在前端对数据进行字符串化,然后在后端对其进行解析。 像这样:
前端 ajax 调用。 我 JSON.stringify 数组数据。
$.ajax({
url: '/postGateway',
method: 'POST',
data: {
analyst: analyst,
building_number: building_number,
commodity_tag: commodity_tag,
meter: meter,
timestamp: JSON.stringify(timestamp),
values: JSON.stringify(values),
reason: JSON.stringify(reason),
notes: JSON.stringify(notes)
},
})
然后我在后端解析 req.body 变量。 现在我的数据完美提交了!
const postdata = JSON.stringify({
'analyst': analyst,
'building_number': building_number,
'commodity_tag': commodity_tag,
'meter': meter,
'data': {
'timestamp': JSON.parse(timestamp),
'value': JSON.parse(values),
'reason': JSON.parse(reason),
'notes': JSON.parse(notes)
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.