成功删除请求后,在 Express.js 中渲染页面时出现问题

问题描述 投票:0回答:1

我正在使用 Node.js 、 MongoDB 和 ejs 构建一个简单的 URL 缩短项目,但我遇到了一个问题,即在成功处理 DELETE 请求后无法呈现页面。 “删除”页面正在浏览器网络选项卡的响应预览中加载,但未显示在主窗口中。 enter image description here

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。

javascript node.js mongodb express ejs
1个回答
0
投票

您需要更新路由以发送重定向信号,而不是在 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>
© www.soinside.com 2019 - 2024. All rights reserved.