【发布时间】:2021-11-25 04:12:13
【问题描述】:
我是一个初学者,我正在尝试通过 axios 从 react 更新带有嵌套对象的记录:
这是我的功能,我尝试了很多东西来使它工作,但没有机会。您可以看到其中很少有人被注释掉。
const saveBlend = async (layout, blocks) => {
try {
const res = await axios({
method: 'PUT',
data: {
layouts: layout,
//layouts: toJSON(layout), ---> From Flatted
//layouts: stringify(layout), ---> From Flatted
//layouts: JSON.stringify(layout),
//blocks: blocks,
title: 'Lorem ipsum dolar sit amet',
},
withCredentials: true,
//headers: { 'content-type': 'application/json' },
url: '/blend/' + blendId,
})
console.log(res.data)
} catch (err) {
if (err.response) {
console.log(err.response.data.message)
} else {
console.log(err.message, 'Something went wrong.')
}
}
}
对象(布局)来自反应状态,如下所示:
{
lg: [{…}, {…}, {…}]
md: [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
sm: [{…}, {…}, {…}]
xs: [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
xxs:[{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
}
或者这个:
const userBlocks = [
{ i: 'b20e4586-b676-447c-9824-b6a9b61115bd', comp: 'Sample', x: 0, y: 0, w: 5, h: 2 },
{ i: '119bf4b4-8689-4ac2-bdd3-a16feb28d548', comp: 'Sample', x: 1, y: 0, w: 3, h: 2 },
{ i: 'f9a70559-0ffe-45eb-aabf-549af484cc80', comp: 'Sample', x: 4, y: 0, w: 1, h: 2 },
{ i: 'e49c1430-9a0b-418a-9312-986e8ff573bb', comp: 'Sample', x: 0, y: 2, w: 2, h: 2 },
{ i: 'b8af2e33-8a4a-482c-843d-b07691e35865', comp: 'Sample', x: 0, y: 2, w: 6, h: 2 },
]
在后端,当我尝试读取发送的值时,它是未定义的。后端看起来像这样:
router.put('/:id', ensureAuth, async (req, res) => {
try {
const requestedUpdates = Object.keys(req.body)
const allowedUpdates = ['layouts', 'blocks', 'home', 'title']
const isUpdatePossible = requestedUpdates.every((update) => {
return allowedUpdates.includes(update)
})
//console.log(JSON.parse(req.body.blocks))
console.log(req.body.layouts)
// console.log(req.body.blocks)
// console.log(req.body.title)
if (!isUpdatePossible) {
return res.status(400).send({ message: 'Some of the requested fields is not possible to update' })
}
const url = req.params.id
// const task = await Task.findByIdAndUpdate(_id, req.body, { new: true, runValidators: true })
const blend = await Blend.findOne({ url: req.params.id, user: req.user[0]._id })
if (!blend) {
return res.status(404).send({ message: 'The blend can not be found' })
}
requestedUpdates.forEach((update) => {
blend[update] = req.body[update]
})
await blend.save()
res.status(201).send(blend)
} catch (e) {
if (e.name == 'CastError') {
return res.status(400).send({ error: 'Invalid blend URL' })
}
console.log(e)
res.status(500).send(e)
}
})
所以,我的问题是:我怎样才能将这些复杂的数据放入、修补、发布到我的后端而不会出现任何问题?所以我可以在处理后读取并保存到我的数据库中?
提前谢谢大家!
【问题讨论】:
-
请更新您的问题 1. 您的数据实际可能是什么样子的示例,2. 您如何尝试在后端读取它。从您分享的内容来看,没有什么太复杂的东西无法通过 http 调用发送。
-
@windowsill 感谢您抽出宝贵时间。我已经添加了后端部分,还有一个我试图发送的实际数组,以及另一个嵌套对象的数据结构。
标签: node.js reactjs json express axios