0

I just started Backend in Node.js Now i want to write a REST api in Node.js that is supposed to send Data into a Mysql Database. The GET request works fine apparently, so there are no Issues whatsoever with the GET Request, just the POST, which does not save information into the Database.

My Code is Looking Like this

app.post('/users/', function(req,res){
let sql ="insert into personal_info (name, email, gender, national_id,salary) values (?)";
let values = [req.body.name, req.body.email, req.body.gender,req.body.national_id,req.body.salary];
db.query(sql, [values], function(err, data, fields){

      if (err) throw err;
      res.json({
        status: 200,
        message: "New user added successfully"
      })
    });
});

Running it inside POSTman i am getting this :

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>Error</title>
</head>

<body>
    <pre>Cannot POST /users</pre>
</body>

</html>

Is there something i appear to be Missing? Like I said, I am very new to this, and I do need clarification of some sort.

Edits

Code Looks Like this Now :

app.post('/api/user/', function(req,res){
  let sql ="insert into personal_info (name, email, gender, national_id,salary) values (?,?,?,?,?)";
  let values = [req.body.name, req.body.email, req.body.gender,req.body.national_id,req.body.salary];
  dbcon.query(sql, [values], function(err, data, fields){
  
        if (err) throw err;
        res.json({
          status: 200,
          message: "New user added successfully"
        })
      });
  });

And here is the Error

D:\Node_JSREST\nodejsrest_example>node index.js
Node app is on port 5900
D:\Node_JSREST\nodejsrest_example\node_modules\mysql\lib\protocol\Parser.js:437
      throw err; // Rethrow non-MySQL errors
      ^

Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '?,?,?,?)' at line 1
    at Query.Sequence._packetToError (D:\Node_JSREST\nodejsrest_example\node_modules\mysql\lib\protocol\sequences\Sequence.js:47:14)
    at Query.ErrorPacket (D:\Node_JSREST\nodejsrest_example\node_modules\mysql\lib\protocol\sequences\Query.js:79:18)
    at Protocol._parsePacket (D:\Node_JSREST\nodejsrest_example\node_modules\mysql\lib\protocol\Protocol.js:291:23)
    at Parser._parsePacket (D:\Node_JSREST\nodejsrest_example\node_modules\mysql\lib\protocol\Parser.js:433:10)
    at Parser.write (D:\Node_JSREST\nodejsrest_example\node_modules\mysql\lib\protocol\Parser.js:43:10)
    at Protocol.write (D:\Node_JSREST\nodejsrest_example\node_modules\mysql\lib\protocol\Protocol.js:38:16)
    at Socket.<anonymous> (D:\Node_JSREST\nodejsrest_example\node_modules\mysql\lib\Connection.js:88:28)
    at Socket.<anonymous> (D:\Node_JSREST\nodejsrest_example\node_modules\mysql\lib\Connection.js:526:10)
    at Socket.emit (events.js:189:13)
    at addChunk (_stream_readable.js:284:12)
    --------------------
    at Protocol._enqueue (D:\Node_JSREST\nodejsrest_example\node_modules\mysql\lib\protocol\Protocol.js:144:48)
    at Connection.query (D:\Node_JSREST\nodejsrest_example\node_modules\mysql\lib\Connection.js:198:25)
    at D:\Node_JSREST\nodejsrest_example\index.js:42:9
    at Layer.handle [as handle_request] (D:\Node_JSREST\nodejsrest_example\node_modules\express\lib\router\layer.js:95:5)
    at next (D:\Node_JSREST\nodejsrest_example\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (D:\Node_JSREST\nodejsrest_example\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (D:\Node_JSREST\nodejsrest_example\node_modules\express\lib\router\layer.js:95:5)
    at D:\Node_JSREST\nodejsrest_example\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (D:\Node_JSREST\nodejsrest_example\node_modules\express\lib\router\index.js:335:12)
    at next (D:\Node_JSREST\nodejsrest_example\node_modules\express\lib\router\index.js:275:10)

D:\Node_JSREST\nodejsrest_example>

Edits Again

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mysql = require('mysql');

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

app.get('/',function(req,res){
    return res.send({error:true, message : 'hello world'});
});

var dbcon = mysql.createConnection({host:'localhost',user:'root',password:'',database:'staffdb' });
dbcon.connect();

app.get('/users',function(req,res){
dbcon.query('select * from personal_info', function (error, results, fields){
    if (error) throw error;
        return res.send({ error: false, data: results, message: 'users list.' });
    });

});

app.get('/users/:id',function (req, res){

    let user_id = req.params.id;
    if (!user_id) {
        return res.status(400).send({ error: true, message: 'Please provide user_id' });
    }

    dbcon.query('select * from personal_info where id=?',user_id,function(error, results,fields){
        if (error) throw error;
        return res.send({ error: false, data: results[0], message: 'users list.' });
    });
});



app.post('/api/user/', function(req,res){
  let sql ="insert into personal_info (name, email, gender, national_id,salary) values (?)";
  let values = [req.body.name, req.body.email, req.body.gender,req.body.national_id,req.body.salary];
  dbcon.query(sql, [values], function(err, data, fields){
  
        if (error) throw error;
        res.json({
          status: 200,
          message: "New user added successfully"
        })
      });
  });


app.listen(5900,function(){
    console.log('Node app is on port 5900');
});

module.exports = app;
Husseiny
  • 45
  • 1
  • 5

1 Answers1

0

I think your using the wrong node module for your database engine. Here you import the mysql:

var mysql = require('mysql');

But in the error we can see that you have an error for a mariaDB server:

Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '?,?,?,?)' at line 1

I suggest you to try with the mariadb node module. Here is an example from mariadb.com. The README is also good.

Dharman
  • 30,962
  • 25
  • 85
  • 135
negrel
  • 96
  • 5