-2

I have a api should receive data to save on database, but when i call the put method my req.body.nome return empty,but when i use the form-urlencoded its work. i tried to use body parser but the body parser is deprecated.

My request put enter image description here

My code

//my server
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')

const app = express();
var corsOptions = {
    origin: 'http://localhost:8001'
};

app.use(cors(corsOptions));

app.use(express.json());
app.use(express.raw())

...

//routers
module.exports = app => {
    const conta = require('../controllers/createCount');
    var router = require('express').Router();

    router.post('/teste', conta.createCount)
    
    app.use('/api', router)
}
// my controller
exports.createCount = (req, res) =>{
    const conta = new Contas({
        Nome: req.body.nome,
        Valor: req.body.valor,
        Historico: req.body.historico,
        DataEmissao: req.body.dataEmissao,
        DataVencimento: req.body.dataVencimento
    });
    conta
        
        .save(conta)
        .then(data => {
            res.send(data)
            console.log(conta)
        })

 
}
 
Matheus Martins
  • 139
  • 1
  • 14
  • "*body parser is deprecated*" - This is **not at all true**. See [this Stack Overflow thread](https://stackoverflow.com/questions/24330014/bodyparser-is-deprecated-express-4). – esqew Mar 29 '21 at 13:31

1 Answers1

1
  1. You've set your body to type "Text" in Postman, which will send an incorrect Content-Type header to your server - open the drop-down menu to the right of the "GraphQL" radio button and set the content type to "JSON".

  2. You're sending invalid JSON - the spec states that single quotes aren't allowed - your keys and values should be encapsulated in double quotes ":

    {
        "nome": "Matheus"
    }
    
esqew
  • 42,425
  • 27
  • 92
  • 132