0

I use node js for backend. I'm trying to update some fields in the user profile by using the ternary operator in frontend and also in backend.

/* Take the user with a SQL statemtnt and after compare with ? operator */
exports.update = (req, res, next) => {

    const { firstName ,lastName ,age ,currentWeight ,targetWeight ,username ,password } = req.body;
    const userID    = req.params.id;
    let oldValues   = `SELECT * FROM users WHERE userID = '${userID}'`;

    let newValues   = `UPDATE users
                    SET 
                    firstName       = '${req.body.firstName      ? firstName      : res[0].firstName  }'  ,
                    lastName        = '${req.body.lastName       ? lastName       : res[0].lastName  }' ,
                    age             = '${req.body.age            ? age            : res[0].age  }' ,
                    currentWeight   = '${req.body.currentWeight  ? currentWeight  : res[0].currentWeight  }' ,
                    targetWeight    = '${req.body.targetWeight   ? targetWeight   : res[0].targetWeight }',
                    username        = '${req.body.username       ? username       : res[0].username }'
                    WHERE userID    = '${userID}' ;`

    db.query(oldValues, (error, result) => {
        if (error)      throw error;
        if (result)     {
            db.query(newValues, (error, result) => {
                if (error)      throw error;
                if (result)     return res.send('User modified!');
            })
        }
    })
}

This is the backend, where I chosen not to require the user update all the information at a time. instead, I get the old information from the user, and if the req.body for an imput is empty, i replace it with the old information.


The problem is now on the front end. There I use plain JS and fetch functions

/* 
    Form elements
*/
const username          = document.querySelector('#username');
const fName             = document.querySelector('#fName');
const lName             = document.querySelector('#lName');
const age               = document.querySelector('#age');
const currentWeight     = document.querySelector('#currentWeight');
const targetWeight      = document.querySelector('#targetWeight');
const editUser          = document.querySelector('.editUser');

const pFName             = document.querySelector('.profileFname');
const pLName             = document.querySelector('.profileLname');
pFName.textContent       = user.user[0].firstName;
pLName.textContent       = user.user[0].lastName;

/* 
    Modify a user details
*/
editUser.addEventListener('click', () => {
const URL = 'http://localhost:3000/api/update/' + user.user[0].userID;

fetch(
    URL,
    {
        method: 'PUT',
        headers: {
            'Authorization': 'Bearer ' + user.token,
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            firstName :         fName ?         user.user[0].firstName      : fName,
            lastName :          lName ?         user.user[0].lastName       : lName,
            age :               age ?           user.user[0].age            : age,
            currentWeight :     currentWeight ? user.user[0].currentWeight  : currentWeight,
            targetWeight :      targetWeight ?  user.user[0].targetWeight   : targetWeight,
            username :          username ?      user.user[0].username       : username})
    }
)
.then(response => response.json())
.then(response => console.log(response))
});


Can somebody tell me please how can I do this? I encounter a JSON problem. In the console:

VM2631:1 Uncaught (in promise) SyntaxError: Unexpected token U in JSON at position 0

daniel sas
  • 257
  • 2
  • 9
  • I forget to mention that in frontend "user.user[0].firstName" is taken from localStorage – daniel sas Jul 28 '21 at 11:25
  • your response to the request is the string "User modified!" - this is not JSON, and you can see where the `U` comes from that the error is complaining about now - try `.then(response => response.text())` – Bravo Jul 28 '21 at 11:37
  • by the way, on the server, what do you expect `res[0].firstName` etc to be? `res` is the response you haven't written yet - fortunately, you ALWAYS send `fname` `lname` etc, so you'll never hit that problem – Bravo Jul 28 '21 at 11:42
  • also, I won't lecture you about the possible SQL injection attack issues your code has – Bravo Jul 28 '21 at 11:44
  • Thanks alot. I just saw the backend error you say now. I am actually surprised it works like that. I corrected the response.text() and I will correct also the res from backend – daniel sas Jul 28 '21 at 11:55
  • Regarding to the possible SQL injection attack issues, I have absolutely no idea how can I protect it. Can you please give me some resources? Thanks – daniel sas Jul 28 '21 at 11:56
  • I'm quoting [this answer](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) - ***you should always use prepared statements and parameterized queries*** - but that link shows PHP, I don't use SQL in node, so I don't know how to "use prepared statements and parameterized queries" - but those phrases "prepared statements" and "paramaterized queries" should be enough to research a solution in node – Bravo Jul 28 '21 at 11:59

0 Answers0