【发布时间】:2021-12-29 18:04:33
【问题描述】:
我正在尝试使用 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。应该是数组的四个变量以奇怪的字符串格式返回,当我尝试使用该变量时,该值为 null,因此没有任何内容传递给 axios 数据。或者例如,如果我尝试 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 调用。我将数据推送到四个空数组中,然后将这些变量设置在下面的数据值中。
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
},
})
【问题讨论】:
标签: javascript node.js ajax axios