gpt4 book ai didi

javascript - 如何 POST 一个包含对象数组的数组?

转载 作者:行者123 更新时间:2023-12-02 22:14:25 25 4
gpt4 key购买 nike

上下文

我正在学习 javascript,同时使用 Node.JS 和 Express 构建 REST API。目前,我一直在尝试读取其中包含对象数组的对象数组。下面是我正在阅读的一个小例子。

[
{
"description":"hhhh",
"goal":"yyyy",
"goalDate":"12/5/2019",
"mSubGoalArray":
[
{
"description":"yyyy",
"goal":"ggggg",
"goalDate":"12/4/2019",
"mSubGoalArray":[]
}
]
},
{
"description":"yy",
"goal":"gg",
"goalDate":"12/11/2019",
"mSubGoalArray":
[
]
}
]

我尝试过什么

我尝试将其设置为 true,然后读取完整字符串。当我去显示已在 VIA postman 中读取的数据时,它显示它已被读取并识别,但它无法在控制台中显示,它显示为 未定义

我还尝试模仿对象中包含的所有字段,并一次只读取一个字段。然而,当我与 API 交互时,它会编译,我最终会收到一个数组,提示在初始化之前无法访问“目标”。

目标.js

const express = require('express');
const router = express.Router();

//getting from the database
router.get('/', (req, res, next) => {

});

//posting to the database
router.post('/', (req, res, next) => {

const Array = req.body.data;
console.log(Array);

/*const goal = [
goal.description = req.body.description,
goal.goal = req.body.goal,
goal.goalDate = req.body.description,
goal.mSubGoalArray = [
mSubGoalArray.description = req.body.description,
mSubGoalArray.goal = req.body.goal,
mSubGoalArray.goalDate = req.body.description,
mSubGoalArray.mSubGoalArray['null'],
]
];*/

res.status(200).json({
the: 'Updated goal'
});
});

module.exports = router;

app.js

const express = require('express');
const app = express();
const morgan = require('morgan');
const bodyParser = require('body-parser');

app.use(morgan('dev'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

const goalsRoutes = require('./api/routes/goals');
const loginRoutes = require('./api/routes/login');

app.use('/goals', goalsRoutes);
app.use('/login', loginRoutes);

module.exports = app;

问题#

我知道 bodyparser 应该允许内部对象。如何显示 JSON 对象中的读取内容,以便确认我已成功传输该对象?我怎样才能摆脱错误目标初始化错误以其他方式进行。

最佳答案

router.post('/', (req, res, next) => {

const tab= req.body;
console.log(Array);
tab.forEach(element=>{

//HERE WE ARE LOOPING ON THE FIRST ARRAY NOW YOU ACCESS TO THE DATA FOR EXAMPLE element.description element.goal and you can also loop inside this loop on the element.mSubGoalArray

})


res.status(200).json({
the: 'Updated goal'
});
});

关于javascript - 如何 POST 一个包含对象数组的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59440386/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com