const express = require('express');
const Url = require('./models/url');
...
app.route('/url/:id').delete(async(req , res) => {
const shortId = req.params.id;
await Url.findOneAndDelete({
shortId
})
res.status(200);
return res.render('deletion' , {
id: shortId,
})
})
...
这是我的ejs代码
...
<body>
<h1>Short URL Created!!</h1>
...
<button onclick="deletefunction('<%= url.shortUrl %>')">Delete URL</button>
<script>
async function deletefunction(url){
await fetch(`/url/${url}` , {
method: 'DELETE'
})
}
</script>
</body>
我预计单击此按钮将从数据库中删除 URL 并呈现另一个 HTMl 页面。但前端页面上什么也没发生,URL 确实从数据库中删除了,但没有加载我期望的 HTML 页面。
我尝试将
res.render()
删除为 res.json()
。同样的情况发生了,页面上没有加载任何内容,但在网络选项卡中检查时正确返回了 json。
您需要更新路由以发送重定向信号,而不是在 ejs 视图脚本标记中处理信号。
app.route('/url/:id').delete(async (req, res) => {
const shortId = req.params.id;
await Url.findOneAndDelete({ shortId });
res.status(200).send({ redirect: '/deletion-page' }); // Send redirect signal
});
然后,对于您的 EJS,您将让信号将您的正文标记替换为删除页面所需的任何内容
...
<body>
<h1>Short URL Created!!</h1>
...
<button onclick="deletefunction('<%= url.shortUrl %>')">Delete URL</button>
<script>
async function deletefunction(url) {
try {
const response = await fetch(`/url/${url}`, {
method: 'DELETE'
});
if (!response.ok) {
throw new Error('Deletion failed');
}
const html = await response.text();
document.body.innerHTML = html; // Replace your current body with the new HTML for your page
} catch (error) {
console.error('An error occurred:', error);
// You could also update the page to show the error by rendering a new 404 ejs page this is recommended for a friendly UI with a redirect to home page button
}
}
</script>
</body>