0

I have this code where I am trying to receive data from the user and it should be inserted into the db directly without any module just a controller, can someone tell me how can I do that, I know we can get the user data in the req.body, but I don't know how to send it back to the controller here is the
P.S user will be sending around 10 or more fields that will be inserted

here is the code controller

 sql.query(`INSERT INTO Admin (LoginID,Password,Preference,Name,Last Name) values ? ` ,  (err, result)=> {
        if (err) {
            console.error('Something bad happened: ' + err);

            return res.status(500);
        }

        console.log('Response from controller', result);
        res.json(result);
    });
}
module.exports = {test}

and this is the router page Router

router.post('/CreateOrganizer',(req,res)=>{
    
    organizer.test
})
Deko96
  • 15
  • 5

1 Answers1

1

This is how you should proceed:


const con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword",
  database: "mydb"
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
});


app.post('',(req, res, next) => {
  
const user = req.body;
   // use the same key in the query that you are getting from body.
  const sql = "INSERT INTO Admin (LoginID,Password,Preference,Name,Last Name) 
  VALUES ('user.LoginID', 'user.Password', 'user.Preference', 'user.Name''user.LastName')";
  con.query(sql, function (err, result) {
    if (err) {
       console.error('Something bad happened: ' + err);
       return res.status(500);
    }
    console.log("1 record inserted");
  });

})

There are several tutorials available online that can help you to achieve the same.

Apoorva Chikara
  • 8,277
  • 3
  • 20
  • 35