2
votes

I'm trying to add a post request to a website but i don't understand the error i'm getting. I'm sending four text element, I'm sure that they are right (size, type) and I manage to add an element manualy in my database without problem. It is not my website, I don't really know how it work so i replicated another request. However the error is saying that one of my element is too long which is not the case so i'm kinda confused.

Here is my POST request

app.post("/api/addOS" , function(req, res) {
    if(!(apikeys[req.query.username]===req.query.apikey) || (req.query.username == undefined) || (req.query.apikey == undefined)) {
        res.json({"error" : "not allowed"});
    } else {
        var con = new Database();
        var query = "INSERT INTO BRAND (name,abbr,color,type) VALUES ('"+req.body.name+"','"+req.body.abbr+"','"+req.body.couleur+"','"+req.body.type+"')";
        con.query(query).then(rows => {          
            res.json(rows);
        });
    }
});

The class Database is defined as follow

class Database {
constructor(  ) {
    this.connection = mysql.createConnection( {
      host: "localhost",
      user: "root",
      password: "pswd",
      database: "dbname"
  } );
}
query( sql, args ) {
    return new Promise( ( resolve, reject ) => {
        this.connection.query( sql, args, ( err, rows ) => {
            if ( err ){
                return reject( err );
            }
            resolve( rows );
        } );
    } );
}
close() {
    return new Promise( ( resolve, reject ) => {
        this.connection.end( err => {
            if ( err )
                return reject( err );
            resolve();
        } );
    } );
}

}

The error displayed on my webpage console is this one

angular.js:14525 Possibly unhandled rejection: {"data":null,"status":-1,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"https://localhost:4443/api/addOS?username=test&apikey=z4oP>3Jocv","headers":{"Accept":"application/json, text/plain, /"},"name":"testtest","abbr":"test","type":"os","couleur":"tre"},"statusText":""}

and the one on my console is this one

(node:15728) UnhandledPromiseRejectionWarning: Error: ER_DATA_TOO_LONG: Data too long for column 'abbr' at row 1 at Query.Sequence._packetToError (C:\wamp64\www\node\node_modules\mysql\lib\protocol\sequences\Sequence.js:47:14) at Query.ErrorPacket (C:\wamp64\www\node\node_modules\mysql\lib\protocol\sequences\Query.js:77:18) at Protocol._parsePacket (C:\wamp64\www\node\node_modules\mysql\lib\protocol\Protocol.js:291:23) at Parser._parsePacket (C:\wamp64\www\node\node_modules\mysql\lib\protocol\Parser.js:433:10) at Parser.write (C:\wamp64\www\node\node_modules\mysql\lib\protocol\Parser.js:43:10) at Protocol.write (C:\wamp64\www\node\node_modules\mysql\lib\protocol\Protocol.js:38:16) at Socket. (C:\wamp64\www\node\node_modules\mysql\lib\Connection.js:91:28) at Socket. (C:\wamp64\www\node\node_modules\mysql\lib\Connection.js:525:10) at Socket.emit (events.js:223:5) at addChunk (_stream_readable.js:309:12) -------------------- at Protocol._enqueue (C:\wamp64\www\node\node_modules\mysql\lib\protocol\Protocol.js:144:48) at Connection.query (C:\wamp64\www\node\node_modules\mysql\lib\Connection.js:201:25) at C:\wamp64\www\node\app.js:92:29 at new Promise () at Database.query (C:\wamp64\www\node\app.js:91:16) at C:\wamp64\www\node\app.js:379:9 at Layer.handle [as handle_request] (C:\wamp64\www\node\node_modules\express\lib\router\layer.js:95:5) at next (C:\wamp64\www\node\node_modules\express\lib\router\route.js:137:13) at Route.dispatch (C:\wamp64\www\node\node_modules\express\lib\router\route.js:112:3) at Layer.handle [as handle_request] (C:\wamp64\www\node\node_modules\express\lib\router\layer.js:95:5) (node:15728) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:15728) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

1
what type is abbr field and how many symbols it's length is? or don't send data longer than 2 or 3 symbols (since test is 4 char long and it's long for abbr field) - num8er
@num8er abbr is type varchar(8) I also already tried with less char - Antoine553

1 Answers

2
votes

I see common level issues:

1) never create connection to database on request time.

2) Your database class allow use of promises with args substitution (? symbols in my example), so use it, it's more secure.

You said abbr field is varchar(8) so req.body.abbr.trim() in my example must clean empty symbols that maybe was the issue.

Please try this code and tell me results.

const db = new Database(); // Connection must be created once

// authorization
const isAuthorized = function(req, res, next) {
  if(
   req.query.username && 
   req.query.apikey && 
   apikeys[req.query.username] === req.query.apikey
  ) {
    return next();
  }

  res.status(401).json({"error" : "not authorized"});
};

app.post(
  "/api/addOS", 
  isAuthorized,
  async function(req, res) {
    try {
      const result = await db.query(
        'INSERT INTO BRAND (name, abbr, color, type) VALUES (?, ?, ?, ?)',
        [req.body.name, req.body.abbr.trim(), req.body.color, req.body.type]
      );
      res.status(201).json(result);
    }
    catch (error) {
      res.status(500).json({message: error.message});
    }
  });