1

I have a post route on my node.js server and I want to send a json object on the body request to insert that on a sql database.

If I use "INSERT INTO users(UserInfo, BitMask) Values ("value1", 1)" it works, but If I try to scape the object like on the example below it doesn't.

I also tried "INSERT INTO users(UserInfo, BitMask) Values ?", [client], But it doesnt work.

  router.post("/add/client", (request, res) => {
     let client = {}
     client.UserInfo = request.body.name;
     client.BitMask = request.body.bitmask;

     pool.request().query("INSERT INTO users(UserInfo, BitMask) Values ?" + mysql.escape(client),
    (err, result)=>{
     if(!err){
         return res.json({ success: true, data: result, records_added: result.affected_rows });
        }
        return res.json({ success: false, data: err });
    })
});

This code returns the following object:

  {
    "success": false,
    "data": {
        "code": "EREQUEST",
        "number": 0,
        "originalError": {
            "sqlstate": "07002",
            "code": 0
        },
        "name": "RequestError"
        }
    }

Anyone knows what I am missing here? One of the answers I have found on google was that The problem comes from using a placeholder multiple times in a query, but it doesn't seem to be the case.

Thanks for the help.

1 Answer 1

2

Use a parameterized query, I'd also opt for async / await syntax for better readability

router.post("/add/client", async (request, res) => {
  try {
    const result = await pool.request()
      .input('userInfo', request.body.name)
      .input('bitmask', request.body.bitmask)
      .query("INSERT INTO users(UserInfo, BitMask) Values (@userInfo, @bitmask)");
    return res.json({ 
      success: true, 
      data: result, // I would avoid this, potential to leak DB info to the client
      records_added: result.affected_rows 
    });
  } catch (e) {
    // consider returning next(e) here and handling errors somewhere common
    return res.json({ 
      success: false, 
      data: err // don't do this, again potential to leak DB info to the client
    });
  }
});
Sign up to request clarification or add additional context in comments.

1 Comment

I accepted the answer because using parameterized query worked just super! Plus the warning about returning result and err on my json objects. Thanks for the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.