我試圖application/x-www-form-urlencoded在我的 node.js 路由中使用編碼的 POST 正文。
在命令列上使用 curl 請求:
curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d 'trx[0][trx_amt]=4166481.208338&trx[0][trx_crdr]=CR&trx[0][trx_tran_type]=TR&trx[0][trx_ref1]=5979NY270557&trx[1][trx_amt]=-5735967.281740&trx[1][trx_crdr]=DR&trx[1][trx_tran_type]=II&trx[1][trx_ref1]=7305XN175748' localhost:8080/api/test
我現在想決議這些值并將它們放入一個陣列陣列中(沒有鍵/值對)。決議請求正文中的值作業正常,將它們也放入陣列 ( current_trx),但將該陣列作為元素推入另一個陣列 ( trx_data) 會使陣列留空。請幫助我了解問題所在。
app.post("/api/test", (req, res) => {
console.log(JSON.stringify(req.headers));
console.log(req.body);
var trx_data = [];
var current_trx = [];
for (let i = 0; i < req.body.trx.length; i ) {
current_trx.push(parseFloat(req.body.trx[i].trx_amt));
current_trx.push(req.body.trx[i].trx_crdr);
current_trx.push(req.body.trx[i].trx_tran_type);
current_trx.push(req.body.trx[i].trx_ref1);
trx_data.push(current_trx); // this seems not to have any effect, trx_data remains empty
console.log("CURRENT_TRX:");
console.log(current_trx); // this works fine, output as expected
// emptying current_trx for the next loop
while (current_trx.length > 0) {
current_trx.pop();
}
}
console.log("TRX_DATA ARRAY"); // empty..
console.log(trx_data);
res.sendStatus(200);
});
uj5u.com熱心網友回復:
你可以使用 Array.map 來解決這個問題,
您正在向 trx_data 添加值并將其清空。您可以var current_trx = [];在回圈內移動,這也將解決洗掉清除邏輯的問題。
app.post("/api/test", (req, res) => {
const trx = req.body.trx;
const trx_data = trx.map((item) => {
const current_trx = [];
current_trx.push(parseFloat(item.trx_amt));
current_trx.push(item.trx_crdr);
current_trx.push(item.trx_tran_type);
current_trx.push(item.trx_ref1);
return current_trx;
});
console.log(trx_data);
res.sendStatus(200);
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/402330.html
標籤:
