TypeError: Cannot read property 'name' of undefined

app.post(’/salvarCliente’, function(request, response) {

var connection = mysql.createConnection({
host : process.env.MYSQL_HOST,
user : process.env.MYSQL_USER,
password : process.env.MYSQL_PASS,
database : process.env.MYSQL_DB
});

connection.connect();

connection.query("insert into dianteco_seguros.dadosusuario values ('"+request.body.name+"','"
               +request.body.profile_pic+"','"
               +request.body.status+"','"
               +request.body.subscribed+"','"
               +request.body.custom_fields.emailUsuario+"')", 
        
 function (error, results, fields) {
console.log('enviou as variaveis') ;   
if (error) throw error;
 connection.end();


  response.json({
    "version": "v2",
    "content": {
        "messages": [
            {
               "type": "text",
               "text": "Cadastro Salvo"
            }
        ]
      }
    });

});

});

I think the problem is with the connection.query where it say:

request.body.name

Do you have in your code the ‘body-parser’ middleware?

Maybe if you share your name project we can help with it

Hello @lelis419! Welcome to the support forum. From what I’m seeing, it looks like you expect request.body to have a bunch of properties (including name), and the error is because those properties aren’t there. There are two things you can do: Be sure you’re using something like body-parser so requests’ bodies are available in the code, and before making the database call you can check to see the properties are there:

if (request.body && request.body.name) {
  /* your code */
} else {
  response.json({ error: "no body included" });
}
1 Like