HTML/EJS:
<div class="Edit-Panel" style="display: none;">
<div class="Edit-Wrapper">
<div class="Editing">
<p class="Edit-Header">Editing:</p>
<p class="UserSelected">#usernamehere</p>
</div>
<div class="Edit-Inputs">
<div class="Input-Bar">
<input id="Edit-Username" class="Edit-Input" type="text" placeholder="Change Username">
<i class="fa-solid fa-user"></i>
</div>
<div class="Input-Bar">
<input id="Edit-Password" class="Edit-Input" type="text" placeholder="Change Password">
<i class="fa-solid fa-lock"></i>
</div>
<div class="Input-Bar">
<select name="User-Level" class="Drop-Down" id="Edit-Organization">
<option value="" disabled selected>Select Organization</option>
<% organizations.forEach(org => { %>
<option value="<%= org.organizationID %>"><%= org.organizationName %></option>
<% }); %>
</select>
</div>
<div class="Input-Bar">
<select name="Role" class="Drop-Down" id="Edit-Role">
<option value="" disabled selected>Edit Role</option>
<option value="Admin">Admin</option>
<option value="Teacher">Teacher</option>
<option value="Student">Student</option>
</select>
</div>
<button class="Edit-Btn" id="Submit-Edit"> Submit Changes </button>
<button class="Edit-Btn" id="Close-Edit"> Cancel </button>
</div>
</div>
</div>
相关前端JS:
const userId = localStorage.getItem('selectedUserId');
const editUsernameInput = document.getElementById('Edit-Username');
const editPasswordInput = document.getElementById('Edit-Password');
const editOrganizationSelect = document.getElementById('Edit-Organization');
const editRoleSelect = document.getElementById('Edit-Role');
const submitEditBtn = document.getElementById('Submit-Edit');
let editedFields = {};
editUsernameInput.addEventListener('input', function () {
editedFields.username = editUsernameInput.value;
});
editPasswordInput.addEventListener('input', function () {
editedFields.password = editPasswordInput.value;
});
editOrganizationSelect.addEventListener('change', function () {
const selectedOption = editOrganizationSelect.options[editOrganizationSelect.selectedIndex];
editedFields.organizationID = selectedOption.value;
console.log('Organization ID:', editedFields.organizationID);
});
editRoleSelect.addEventListener('change', function () {
editedFields.role = editRoleSelect.value;
});
submitEditBtn.addEventListener('click', function () {
console.log(editedFields.organizationID);
const requestBody = { userId, ...editedFields };
fetch('/api/useredit', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(requestBody)
})
.then(response => {
if (response.ok) {
alert('Changes submitted successfully.');
editedFields = {};
editUsernameInput.value = '';
editPasswordInput.value = '';
editOrganizationSelect.selectedIndex = 0;
editRoleSelect.selectedIndex = 0;
} else {
alert('Error submitting changes.');
}
})
.catch(error => {
alert('Error submitting changes:', error);
});
});
后端:
const express = require('express');
const router = express.Router();
const DBconnection = require('../DB/Connector');
router.post('/useredit', (req, res) => {
const { userId, username, password, organizationID, role } = req.body;
console.log('Received Organization ID:', organizationID);
let updateFields = [];
let updateValues = [];
if (username) {
updateFields.push('UserName = ?');
updateValues.push(username);
}
if (password) {
updateFields.push('UserPassword = ?');
updateValues.push(password);
}
if (role) {
updateFields.push('UserRole = ?');
updateValues.push(role);
}
if (updateFields.length === 0) {
return res.status(400).json({ error: 'No fields to update' });
}
updateValues.push(userId);
const updateUserQuery = `UPDATE useraccounts SET ${updateFields.join(', ')} WHERE UserID = ?`;
DBconnection.query(updateUserQuery, updateValues, (err, updateUserResult) => {
if (err) {
console.error("Error updating user:", err);
return res.status(500).json({ error: 'Error updating user' });
}
if (organizationID) {
const updateSectionLinkQuery = `UPDATE sectionlinks SET SectionID = ? WHERE UserID = ?`;
const updateSectionLinkParams = [organizationID, userId];
DBconnection.query(updateSectionLinkQuery, updateSectionLinkParams, (err, updateSectionLinkResult) => {
if (err) {
console.error("Error updating sectionlink:", err);
return res.status(500).json({ error: 'Error updating sectionlink' });
}
console.log('Section Link Update Result:', updateSectionLinkResult);
return res.status(200).json({ message: 'User updated successfully' });
});
} else {
return res.status(200).json({ message: 'User updated successfully' });
}
});
});
module.exports = router;
为什么我收到 POST http://localhost:3000/api/useredit 400(错误请求) 每当我尝试更改/更新给定的用户组织时。我可以更改用户、用户名、密码和角色。但是当我尝试更改组织时,我收到了错误的请求。
通过控制台日志,我已经验证在前端正在获取正确的组织 ID 并将其发送到后端,并且第一个控制台日志还返回正在接收正确的组织 ID。
但是所有其他日志都过去了
if (organizationID)
不返回任何内容,并且数据库不会发生任何更改。
感谢任何帮助,请不要太严厉。
总的来说,我对后端代码的处理方式做了一些改变,但保留了大部分以前的代码
const express = require('express');
const router = express.Router();
const DBconnection = require('../DB/Connector');
router.post('/useredit', (req, res) => {
const { userId, username, password, organizationID, role } = req.body;
console.log('Received Request Body:', req.body);
// Initialize an array to store the promises for each update operation
const updatePromises = [];
// Update user details if provided
if (username || password || role) {
const updateFields = [];
const updateValues = [];
if (username) {
updateFields.push('UserName = ?');
updateValues.push(username);
}
if (password) {
updateFields.push('UserPassword = ?');
updateValues.push(password);
}
if (role) {a
updateFields.push('UserRole = ?');
updateValues.push(role);
}
const updateUserQuery = `UPDATE useraccounts SET ${updateFields.join(', ')} WHERE UserID = ?`;
const updateUserParams = [...updateValues, userId];
updatePromises.push(new Promise((resolve, reject) => {
DBconnection.query(updateUserQuery, updateUserParams, (err, updateUserResult) => {
if (err) {
console.error("Error updating user:", err);
reject('Error updating user');
} else {
resolve('User details updated successfully');
}
});
}));
}
// Update user's organization if provided
if (organizationID !== undefineda) {
const updateSectionLinkQuery = `UPDATE sectionlinks SET SectionID = ? WHERE UserID = ?`;
const updateSectionLinkParams = [organizationID, userId];
updatePromises.push(new Promise((resolve, reject) => {
DBconnection.query(updateSectionLinkQuery, updateSectionLinkParams, (err, updateSectionLinkResult) => {
if (err) {
console.error("Error updating sectionlink:", err);
reject('Error updating sectionlink');
} else {
resolve('User organization updated successfully');
}
});
}));
}
// Execute all update operations asynchronously
Promise.all(updatePromises)
.then(messages => {
res.status(200).json({ messages });
})
.catch(error => {
res.status(500).json({ error });
});
});
module.exports = router;