[Fixed] post empty when i use post raw in the postman (node js)

Issue

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)
        })

 
}
 

Solution

  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"
    }
    

Leave a Reply

(*) Required, Your email will not be published