node.js - NodeJS - 在 res.render() 之后快速重新加载页面

标签 node.js mongodb express

我使用 MongoDB 和 NodeJS(带有 Express Framework)。

我实际上做了什么:

  • 抓取 MongoDb 中的一些数据
  • 渲染此数据。

我想做的事情:

过滤特定项目。

过滤后的结果都是正确的,但我的问题是页面会渲染两次。

如何防止这种情况发生?

我有一个主上下文根,实际上看起来像这样:

app.get('/main', auth, function(req, res) {
    getItems(req, res, function(results) {
        renderResults(req, res, results);
    });
});

这是我的渲染结果函数:

function renderResults(req, res, results) {

  console.log("In Rendermethode arrived:");
  console.log(results.items);

    res.render('pages/main', {
        offerings: results.items,
        ownUser: {
            id: req.session.user || ""
        },
        filterObj: {
            isActivated: typeof results.filterObj !== 'undefined',
            filterFor: typeof results.filterObj !== 'undefined' ? results.filterObj.filter : "",
            filterText: typeof results.filterObj !== 'undefined' ? results.filterObj.filterText : ""
        }
    });
}

我所做的是在前端发送请求:

$("button.doSearch").on("click", function(e) {
    var dFilter = $("div.filterDropdown button").attr("value") || "",
        dFilterText = $("input.searchterm").val() || "";

    $.post("/search", {
            filter: dFilter,
            filterText: dFilterText
        },
        function(data, status) {
        });
});

这是搜索的后端片段:

app.post('/search', auth, function(req, res) {
    console.log("Filterrequest received.");
    getItems(req, res, function(results) {
        renderResults(req, res);
    });
});

最佳答案

我认为您正在渲染同一 View 两次,因为您在 get 和 post 请求中都调用了 renderResults 函数

问题:

您发出的第一个 HTTP 请求是对 /main url 的 GET 请求,express 会处理它并呈现 pages/main View

第二个请求是发送到 /search url 的 xhr post,express 将处理它并呈现相同的 View pages/main (整个页面)

将整个页面渲染到 AJAX 对象是没有意义的,相反,您可以渲染 JSON 对象并使用 native javascript 或 JQuery 更新页面

解决方案:

根据请求类型呈现不同类型的数据(xhr 不是):

function renderResults(req, res, results) {

    var result = {
        offerings: results.items,
        ownUser: {
            id: req.session.user || ""
        },
        filterObj: {
            isActivated: typeof results.filterObj !== 'undefined',
            filterFor: typeof results.filterObj !== 'undefined' ? results.filterObj.filter : "",
            filterText: typeof results.filterObj !== 'undefined' ? results.filterObj.filterText : ""
        }
    };

    if (!req.xhr) {

        return res.render('pages/main', result);

    }

    res.json(result);
}

关于node.js - NodeJS - 在 res.render() 之后快速重新加载页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47226219/

相关文章:

javascript - 如何在 Javascript 中实现 map,其中值是一个类似于 Java 的字符串数组?

php - 将 mongo 查询转换为 php mongo

arrays - 在 Mongodb 子文档数组中,有没有办法在每个子文档中添加一个新字段

node.js - Strapi API : Set custom query service to find nearest location within a range?

node.js - 使nodejs "require"路径独立?

image - 如何使用node-webkit创建临时图像文件?

javascript - 'res.json(..)' 和 'return res.json(..)' 之间的 Nodejs 区别

javascript - 为什么我的架构不在 Mongoose 数组中添加默认值?

javascript - 在单个 .js 文件中快速路由

node.js - 带有 Passport NodeJ 的集群