我正在尝试创建“编辑个人资料”页面,以便用户可以编辑他/她的个人资料信息。但我在某个地方搞砸了,它不起作用。我假设我在查询部分犯了一个错误。
我的控制器(API):
export const editUser = (req, res) => {
const q = "SELECT * FROM users WHERE id = ?";
const userId = req.params.userId;
db.query(q, [userId], (err, data) => {
if (err) return res.status(409).json(err);
const q = "UPDATE users SET (`name`, `surname`, `headline`) VALUES (?)";
const values = [req.body.name, req.body.surname, req.body.headline];
db.query(q, [values], (err, data) => {
if (err) return res.status(500).json(err);
return res.status(200).json("User has been updated.");
});
});
};
我的路线(API):
const router = express.Router();
router.post("/edit-profile/:userId", editUser);
export default router
我的客户站点代码:
const [err, setErr] = useState(null);
const [inputs, setInputs] = useState({ name: "", surname: "", headline: "" });
const handleChange = (e) => {
setInputs((prev) => ({ ...prev, [e.target.name]: e.target.value }));
console.log(inputs);
};
const handleClick = async (e) => {
e.preventDefault();
try {
await axios.post("http://localhost:8800/api/users/edit-profile/" + userId, inputs);
} catch (err) {
setErr(err.response.data);
}
};
HTML:
<form action="a">
<div>
<p>Name:</p>
<input
type="text"
placeholder={error ? "Something Went wrong" : isLoading ? "Loading" : data.name}
name="name"
onChange={handleChange}
/>
</div>
<div>
<p>Surname:</p>
<input
type="text"
placeholder={error ? "Something Went wrong" : isLoading ? "Loading" : data.surname}
name="surename"
onChange={handleChange}
/>
</div>
<div>
<p>Headline:</p>
<input
type="text"
placeholder={error ? "Something Went wrong" : isLoading ? "Loading" : data.headline}
name="headline"
onChange={handleChange}
/>
</div>
</form>
为了更简单,我尝试在 Insomnia 中发帖:
{
"name": "asd",
"surname": "asd",
"headline": "asd"
}
但我收到错误:
{
"code": "ER_PARSE_ERROR",
"errno": 1064,
"sqlMessage": "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(`name`, `surname`, `headline`) VALUES ('asd', 'asd', 'asd')' at line 1",
"sqlState": "42000",
"index": 0,
"sql": "UPDATE users SET (`name`, `surname`, `headline`) VALUES ('asd', 'asd', 'asd')"
}
我想编辑用户的用户名、姓氏和标题。
update
语句没有values
子句,而是一系列column=value
部分。您还缺少一个 where
子句,仅更新您获得 ID 的用户:
const q =
"UPDATE users SET `name` = ?, `surname` = ?, `headline` = ? WHERE `id` = ?";
const values = [req.body.name, req.body.surname, req.body.headline, userId];