javascript - 如何在 Node.js/ReactJS 中按 ID 正确使用 DELETE
问题描述
我想解释一下我今天遇到的问题。
我认为这比平时更难,所以让我解释一下
在这里,我首先得到一个
getRandom = async () => {
const res = await axios.get(
entrypoint + "/alluserpls"
)
this.setState({ data: res.data })
}
componentDidMount() {
this.getRandom()
}
这是我的删除方法
handleSubmit = (e) => {
e.preventDefault();
const config = {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
};
const url = entrypoint + "/alluserpls";
fetch(url, config)
.then(res => res.json())
.then(res => {
if (res.error) {
alert(res.error);
} else {
alert(`ajouté avec l'ID ${res}!`);
}
}).catch(e => {
console.error(e);
}).finally(() => this.setState({ redirect: true }));
}
然后我映射它
render() {
let datas = this.state.data.map((datass, index) => {
return (
<Col sm="12" key={index}>
<form onSubmit={this.handleSubmit}>
<button type="submit">Delete</button>
</form>
<div>{datass.name}</div>
</Col>
然后我在我的地图上返回结果
return (
<div>
{datas}
</div>
所以可以正常工作,但是当我只想删除 1 张卡时,问题如下,它会删除我所有的 BDD
这是我在 BDD 上的路线
app.delete('/api/alluserpls', (req, res, ) => {
const formData = req.body;
connection.query('DELETE FROM alluserpls SET ?', formData, err => {
if (err) {
res.status(500).send("Erreur lors de la modification des users");
} else {
res.sendStatus(200);
}
});
});
我希望当我点击删除它只删除卡而不是我的所有数据库。
我该如何解决这个问题?
解决方案
这是一种方法,将id
用户分配给按钮id
属性字段,然后与用户一起调用删除 APIid
handleSubmit = (e, id) => {
e.preventDefault();
const userIdData = { id };
const config = {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(userIdData),
};
const url = entrypoint + "/alluserpls";
fetch(url, config)
.then(res => res.json())
.then(res => {
if (res.error) {
alert(res.error);
} else {
alert(`ajouté avec l'ID ${res}!`);
}
}).catch(e => {
console.error(e);
}).finally(() => this.setState({ redirect: true }));
, 在 render 方法中你可以将id
as 变量传递给handleSubmit
函数
render() {
let datas = this.state.data.map((datass, index) => {
return (
<Col sm="12" key={index}>
<form onSubmit={(e) => this.handleSubmit(e, datass.id)}>
<button type="submit">Delete</button>
</form>
<div>{datass.name}</div>
</Col>
在后端,您可以获得 id 并仅删除特定用户
app.delete('/api/alluserpls', (req, res, ) => {
const formData = req.body;
const userId = req.body.id;
const deleteQuery = `DELETE from alluserpls WHERE id = ${userId}`;
connection.query(deleteQuery, err => {
if (err) {
res.status(500).send("Erreur lors de la modification des users");
} else {
res.sendStatus(200);
}
});
});
推荐阅读
- delphi - 如何在运行时将 SVG 文档文本手动插入 TWebBrowser?
- c# - 在 HttpModule (ASP.NET WebForms) 中访问 POST 请求的会话
- math - 在旋转面上构建几何图形
- django - 我想使用其他后端来验证我的后端
- python - 如何解决“发生错误(InvalidClientTokenId)”AWS Chalice 部署错误
- jmeter - JMeter 线程组加速时间加持续时间问题
- cobol - 记录行/输出行中的第一个计算记录在 COBOL 中的输出中变为空白
- tensorflow - 准备音频文件以发送到 TensorFlow 模型服务器
- bash - 使用 pam_systemd.so 自定义 XDG_RUNTIME_DIR
- django - Django 查找外键表单字段(新手问题)