简体   繁体   中英

Express not working with spread operator in JavaScript

I'm coding an app where you send by Axios a form, and it posts on a form controlled by Express. But in my app.post(), I have a ...req.body , which is not showing at the result.

  function exibirResultado(id, dados){
            const texto = JSON.stringify(dados)
            document.getElementById(id).innerHTML = texto
        }

 axios.post('formulario', {
            nome: 'João',
            sobrenome: 'Silva'
        }).then(resp => exibirResultado('post', resp))

That's my client code

app.post('/formulario', (req, res) => {
    res.send({
        ...req.body,
        id: 5
    })
})

In the HTML, there is a div with id post but on it, it only appears the form id attribute.

Are you using the express json middleware? if not, express may be having problems parsing the body. try some thing like this:

const exp = require("express")
const _server = exp()
_server.use(exp.json())

Req.body should be an object, the proof of that is its usage - you can do:

const newComment = new Comment({
        body: req.body.body,
        author: req.body.author
    });

so if I am not mistaken, you cannot use a spread operator on that, since it's not an array. Just send req.body without the spread operator:

app.post('/formulario', (req, res) => {
    res.send({
        req.body,
        id: 5
    })
})

If you need it to be sent as an array, wrap it in a pair of brackets like this:

[req.body]

If you were to add it to an existing array, then you could use the spread operator like this:

[...req.body]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM