0

I'm trying to create this API with NodeJS, Express and Mysql but when testing on Postman, while the code is working to update the values on the database, it doesn't read the info I insert in the body of the request. For example, I can access the params info (codAluno), but not the request body (Empresa_Atual).

I have two files for the API: routes.js and index.js

const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const db = require('./routes')
const port = 3000

app.use(
  bodyParser.urlencoded({
    extended: true,
  })
)
app.use(bodyParser.json())

app.get('/', (request, response) => {
  response.json({ info: 'API' })
})
app.get('/alunos', db.getAlunos)
app.get('/alunos/:id', db.getAlunoByCod)
app.post('/alunos/:id',db.updateAluno)

app.listen(port, () => {
  console.log(`App running on port ${port}.`)
})

and routes.js

const mysql = require('mysql');

// Set database connection credentials
const config = {
  host: 'localhost',
  user: 'user',
  password: '',
  database: 'student',
};

// Create a MySQL pool
const pool = mysql.createPool(config);
const updateAluno = (request, response) => {
  const codAluno = parseInt(request.params.id)
  var Empresa_Atual = request.body.Empresa_Atual
  pool.query('UPDATE aluno SET `Empresa_Atual`= ? WHERE `codAluno` = ?', [Empresa_Atual, codAluno], (error, result) => {
    if (error) throw error;
    response.send('User updated successfully.');
  });
}

This is the request I'm sending via postman

enter image description here

For example, the variable Empresa_Atual is always null even though I assigned it to the request body.

Can anyone help? Thanks!

derpirscher
  • 14,418
  • 3
  • 18
  • 35
mrma
  • 1
  • Add some debugging info, to find out where your information is. (and to verify it is where you think it is) – Luuk Jan 17 '22 at 19:35
  • Add the request you are trying to send to the question ... – derpirscher Jan 17 '22 at 19:47
  • Did you even export anything in routes? – code Jan 17 '22 at 20:06
  • The request you are sending is of type "formdata" (ie has mimetype `multipart/form-data`) but you are only decoding bodies of mimetype `application/json` and `application/x-www-form-urlencoded`. Depending on which side is correct, either change the mimetype in your postman request or see this question on how to hande `multipart/form-data` in express https://stackoverflow.com/questions/37630419/how-to-handle-formdata-from-express-4 – derpirscher Jan 17 '22 at 21:03
  • Does this answer your question? [How to handle FormData from express 4](https://stackoverflow.com/questions/37630419/how-to-handle-formdata-from-express-4) – derpirscher Jan 17 '22 at 21:05

1 Answers1

0

I had the same problem. I had the following: req.params.id. I then changed it to req.params['id'] and it started working. Apparently, the req.params was an object instead of a single value.