【发布时间】:2021-11-19 05:17:51
【问题描述】:
我正在构建一个应用程序,我的 get 或 post 路线没有问题,但我挂断了这条删除路线。
我已经像这样设置了我的前端 javaScript。第一个函数接收数据并使用模板文字动态创建 HTML。
//Populates Storms From Database
fetch("/api/data/storm", {
method: "get",
headers: {
Accept: "application/json, text/plain, */*",
"Content-Type": "application/json"
}
})
.then(response => {
return response.json();
})
.then(data => {
console.log(data)
data.forEach(storm => {
console.log(storm.stormName);
const stormContainer = `
<div class="item">
<div class="content">
<div class="header">
<a class="storm-val" value="${storm._id}">${storm.stormName}</a>
</div>
February 2021
</div>
<form>
<i type="submit" value="${storm._id}" class="delete-storm trash alternate outline icon" action="/api/data/storm/${storm._id}"></i>
</form>
</div>
`
$('#stormsEl').append(stormContainer);
});
});
下一个函数旨在从数据库中删除风暴。我意识到这里有一些真正可怕的代码,但它确实给了我点击风暴的 id。
$(document).on("click", '.delete-storm', (evt) => {
let oldStormId = evt.currentTarget.parentNode.parentNode.childNodes[1].childNodes[1].childNodes[1].getAttribute("value")
// oldStorm = oldStorm.replace(/ /g, "-").toLowerCase();
console.log(oldStormId)
// console.log($(this).siblings(".content").children(".header").children(".storm-val"))
fetch(`/api/data/storm:${oldStormId}`, {
method: "delete",
// body: JSON.stringify(newEmployeeData),
headers: {
Accept: "application/json, text/plain, */*",
"Content-Type": "application/json"
}
})
.then(response => {
console.log(response)
return response.json();
})
.then(data => {
console.log(data)
})
})
我使用 express 连接我的路线以在此处点击控制器,该控制器用于发布和获取风暴。
const router = require("express").Router();
const {
createStorm,
getStormWithShifts,
createShift,
getAllShifts,
getAllStorms,
deleteStorm
} = require('../../controllers/shiftController');
//all routes in this file start with /api/data/
router.route('/storm').post(createStorm).get(getAllStorms);
router.route('/storm').get(getAllStorms);
router.route('/storm/:stormId').delete(deleteStorm);
router.route('/storm/:stormId').get(getStormWithShifts);
router.route('/shift').post(createShift).get(getAllShifts);
module.exports = router;
这就是无论我怎么尝试都无法建立连接的地方。
async deleteStorm(req, res) {
console.log("hello")
await Storm.findOneAndRemove({ _id: req.params.stormId })
.then(dbStormData => {
if (!dbStormData) {
return res.status(404).json({ message: 'No storm with this id!' });
}
res.json({ message: 'Storm successfully deleted!' });
})
}
有什么想法吗?
【问题讨论】: