【问题标题】:Passing in data to my ejs view when redirecting重定向时将数据传递到我的 ejs 视图
【发布时间】:2020-06-06 14:25:59
【问题描述】:

当用户重定向到主页时,我试图将数据从我的登录页面发送到我的主页,以便我可以在主页 ejs 文件中使用信息。

这是我的代码:


    module.exports = function (app) {

        app.post('/login', function (req, res) {
            var data = {
                "email": req.body.email,
                "password": req.body.password
            }

            functions.callAPI("api link", data, function (error, result) {
                if (error) {
                    var response = {
                        "status": 400,
                        "message": error,
                        "data": null
                    }
                    res.render('login', { response: response });
                } else {
                    var response = result;
                    if (response.status === 400) {
                        res.render('login', { response: response });
                    } else {
                        req.session.token = response.data[0].token;
                        req.session.id = response.data[0].id
                        res.redirect('/home', { response: response }); //this is where i what to pass the data.
                    }
                }
            });


        });

    }

【问题讨论】:

    标签: javascript node.js express npm ejs


    【解决方案1】:

    比如说,如果你的 app.get('/home') 的回调是 res.render('home')

    改变 res.redirect('/home', { response: response });

    res.render('home', { response: response });

    编辑 1:

    由于您的评论表明您的 get('/home') 路由不仅仅是渲染主页,因此请按以下方式进行:

    在这个处理 app.post('/login') 的模块中,不是合并整个路由逻辑,而是只返回回调,在 server.js 中将其命名为 loginCallback(或 app.js 或 index.js)

    并制作另一个模块返回app.get('/home')的回调,将其命名为homeCallback,使其接受另一个参数,用于响应,默认参数为空对象。

    现在这个 loginCallback 将调用 homeCallback,传递第三个参数。

    这样可以达到你的目的。

    【讨论】:

    • 这个res.render('home', { response: response }); 只会渲染主视图,但路由仍然是登录路由而不是主路由
    • 然后以这种方式进行:....(不能在评论中使用新行,我将编辑我的答案,请稍等)。
    • @codabae 我已经编辑了我的答案。请尝试。如果还是不明白,请出示你的入口js脚本和app.get('/home') js脚本,我可以说的更详细。
    猜你喜欢
    • 2016-10-06
    • 2016-09-25
    • 2018-03-11
    • 1970-01-01
    • 2017-08-26
    • 2019-05-26
    • 1970-01-01
    • 1970-01-01
    • 2015-06-28
    相关资源
    最近更新 更多