javascript - 当我尝试在 javascript 中获取对象时出现 JSON 错误
问题描述
我使用 node js 作为后端。我正在尝试通过在前端和后端使用三元运算符来更新用户配置文件中的某些字段。
/* 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!');
})
}
})
}
这是后端,我选择不要求用户一次更新所有信息。相反,我从用户那里获取旧信息,如果输入的 req.body 为空,我将其替换为旧信息。
现在问题出在前端。在那里我使用普通的 JS 和 fetch 函数
/*
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))
});
有人可以告诉我,我该怎么做?我遇到了 JSON 问题。在控制台中:
VM2631:1 未捕获(承诺中)SyntaxError:JSON 中位置 0 处的意外标记 U
解决方案
推荐阅读
- python - 单击kivy按钮时如何调用函数?
- ruby-on-rails - Dockerized nmap 显示不正确的操作系统版本
- python - 基于 DateTime 列合并两个熊猫数据框
- html - 试图改变甚至列表链接css?
- typescript - 如何使用打字稿设置自定义 node_modules 路径
- javascript - Leaflet.js gdpr 兼容集成
- python - 如何限制我的图表在 matplotlib 中低于零
- python - cv2.imwrite("resized_"+image, re) 抛出语法错误
- javascript - 在 React Native 中使用构造函数创建对象
- c++ - C ++中的滑动窗口中位数