使用Fetch删除用户端点



我正在建立一个用户网站,管理员应该能够删除用户。我的项目是使用Azure SQL数据库构建。在我的控制器文件中,我有一个端点deleteUser

deleteUser

const deleteUser = (req, res) => {
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
const { id } = req.query
request.query(
`DELETE FROM users where User_ID = '${id}'`,
function (err, recordset) {
if (err) {
console.log(err);
} else if (!id) {
res.json("Please provide an ID")
} else {
res.json(`User with ID: ${id} has been deleted!`)
}
}
);
});
};

我正在尝试使用fetch和EJS对这个端点进行调用。

我的代码在EJS脚本标签

<script>
document.getElementById('deleteUserBtn').addEventListener('submit', (e) => {
e.preventDefault();
fetch('http://localhost:3000/deleteUser', {
method:'DELETE',
headers: {
"Content-Type": "application/json",
},
body: null
})
.then((response) => console.log(response))
.catch((e) => {
console.log(e)
})
})
</script>

我控制台记录响应,所以路由必须是好的,但它似乎没有解析ID到取回。正确的做法是什么?

提前感谢!

解决方案我已经提出了以下解决方案-这不是最好的,但有效。

document.getElementById('deleteUserBtn').addEventListener('submit', (e) => {
e.preventDefault();
// delete user using fetch
const id = document.getElementById('userId').textContent
fetch(`http://localhost:3000/deleteUser?id=${id}`, {
method:'DELETE',
headers: {
"Content-Type": "application/json",
},
body: null
})
.then((response) => console.log(response))
.catch((e) => {
console.log(e)
})
})

感谢您的贡献!

id不应该在获取请求的URL中吗?您正在从请求参数中请求id,因此它可能应该被附加到路径中,如

const id = wherever your id comes from; 
fetch('http://localhost:3000/deleteUser?id=${id}...'

你也需要在你的按钮方法中获取用户的id,但需要更多的代码来查看它来自哪里。

通常使用ID来删除是最好的方法

fetch('http://localhost:3000/deleteUser/:id...'

但是,你可以在body, params, query甚至header中传递id)

最新更新