我正在嘗試使用 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 protected]',
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
},
})
uj5u.com熱心網友回復:
弄清楚了。我只需要在前端對資料進行字串化,然后在后端決議它。像這樣:
前端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)
}
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/363956.html
標籤:javascript 节点.js 阿贾克斯 公理
