如何通过Axios从react到节点发布复杂对象?



我是一个初学者,我正试图通过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)
}
})

所以,我的问题是:我怎么能把,补丁,张贴这些复杂的数据到我的后端没有任何问题?所以我可以读取和保存到我的数据库后处理?

提前感谢大家!

Body包含在请求Body中提交的数据的键值对。默认情况下,它是未定义的,并在使用express.json()或express.urlencoded()等体解析中间件时填充。

服务器代码:

const express = require('express');
const app = express();
const port = 3000;
app.use(express.json()); // for parsing application/json
app.use(express.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.put('/some/path', (req, res) => {
console.log('data from the client', req.body);
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});

客户机代码:

const axios = require('axios');
axios.put('http://localhost:3000/some/path', {
firstName: 'hello',
lastName: 'world'
});

现在可以在服务器日志中看到数据。

$ node express_server.js
Example app listening at http://localhost:3000
data from the client { firstName: 'hello', lastName: 'world' }

最新更新