【问题标题】:How to post complex object from react to node via Axios?如何通过 Axios 将复杂对象从反应发布到节点?
【发布时间】: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


【解决方案1】:

req.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' }

【讨论】:

  • 感谢您的回复。实际上我已经在使用 express.json() 和 express.urlencoded()。我觉得这与我要发布的数据的结构有关。在我的问题中,我有一个数组作为样本(块)如果您可以尝试通过 axios 在您的设置上发布它,是否有机会?因为我真的尝试了这么多组合,但是由于某种原因,我无法获取服务器端的数据。顺便说一句,如果我只发送常规文本,那很好,一切都按预期工作。
  • @Enes 数组按预期序列化。我的设置适用于以下请求 axios.put('http://localhost:3000/some/path', { layouts: { lg: [{ a: 1 }, { b: 2 }] } });
  • @Enes 尝试将app.use(express.json()) 放在服务器代码的顶部,就在const app = express() 的下方。
  • 我已经用您尝试过的示例数据进行了尝试:{ layouts: { lg: [{ a: 1 }, { b: 2 }] } }) 它奏效了。然后,我用我自己的来自反应状态的数据替换了它,但它失败了。数据本身很好,因为当我控制台它时,一切似乎都很好。但是由于某种原因,如果我将它传递给 axios,它就会失败。从使用状态传递数据是否可以,还是在传递之前我应该​​做些什么?非常感谢您的帮助,非常感谢!
  • 哦,app.use(express.json())的位置也如你所说。
猜你喜欢
  • 2013-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多