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