'Req.body return empty object with postman
Good morning, I have a question. I am learning express making a transaction api. I have my put and post methods made with a console.log to see the values. But when I make the request with INSOMNIA, it returns an empty object. Look for possible answers to the problem. I already tried installing body-parser manually, changed the way of importing it and also changed the content-type to application/json but nothing works. Any advice is appreciated, ty in advance.
transaction.js
const express = require('express');
const res = require('express/lib/response');
const router = express.Router();
const mysqlConnection = require('../database');
router.get('/', (req, res) => {
mysqlConnection.query('SELECT * FROM transactions', (err, rows, fields) => {
if(!err) {
res.json(rows)
} else {
console.error(err)
}
});
});
router.get('/:id', (req, res) => {
const {id} = req.params
mysqlConnection.query('SELECT * FROM transactions WHERE id = ?', [id], (err, rows, fields) =>{
if(!err) {
res.json(rows[0])
} else {
console.error(err)
}
})
})
// Borrar transaccion
router.delete('/:id', (req, res) => {
const { id } = req.params;
mysqlConnection.query('DELETE FROM Transactions WHERE id = ?', [id], (err, rows, fields) => {
if(!err) {
res.json({status: 'Transaction Deleted'});
} else {
res.json({status: 'ERROR '+err});;
}
});
});
// Editar transaccion
router.put('/:id', (req, res) => {
const {type, date, name, amt} = req.body;
const {id} = req.params;
console.log(type,date,name,amt)
console.log(id)
query = "UPDATE transactions SET type = '"+type+"', name= '"+name+"', date= '"+date+"',amt = '"+amt+"' WHERE id = "+id;
console.log(query);
mysqlConnection.query(query, null, (err, rows, fields) => {
if(!err) {
res.json({status: 'Transaction Saved'});
} else {
console.log(err);
}
});
});
exports.transactions = router
index.js
const express = require('express')
const app = express()
const routes = require("./routes/transactions")
//Settings
app.set('port', process.env.PORT || 3500)
//Middlewares
app.use(express.json());
//Routes
app.use("/", routes.transactions)
//Crear servidor con el puerto
app.listen(app.get('port'), () => {
console.log('Hola Mundo', app.get('port'))
})
module.exports = app;
database.js
const mysql = require('mysql');
const mysqlConnection = mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: '',
database: 'operations',
})
mysqlConnection.connect(function(err){
if(err) {
console.log(err);
return
} else {
console.log('Db is connected')
}
})
module.exports = mysqlConnection;
example of values
{
"id": 9,
"type": "Ingreso",
"date": "2022-01-09T03:00:00.000Z",
"name": "Trading",
"amt": 25000
},
{
"id": 10,
"type": "Egreso",
"date": "2022-01-10T03:00:00.000Z",
"name": "Patente",
"amt": 4500
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
