简体   繁体   English

在Load Pug上调用​​javascript函数-使用param设置localStorage

[英]Calling javascript function on load pug - setting localStorage with param

What I am attempting to do is invoke a JS function from a pug template that will set an item on the localStorage . 我想做的是从一个pug模板调用一个JS函数,该模板将在localStorage上设置一个项目。 The value of this item will be a param that was passed to the pug template "token" . 该项目的值将是已传递给哈巴狗模板“ token”的参数

Similar questions have been asked in the past and I took inspiration from these answers as they seem to be similar: 过去曾问过类似的问题,我从这些答案中汲取了灵感,因为它们似乎很相似:

My resulting code is: 我得到的代码是:

users.js users.js

import setToken from "../src/setToken";

router.post("/signin", (req, res) => {
    ...

    cognitoUser.authenticateUser(authenticationDetails, {
        onSuccess: function(result) {
            res.render("congrats", {
                title: "Congrats",
                token: result.getAccessToken().getJwtToken(),
                setToken: setToken
            });
        },
        onFailure: function(err) {
            next(err);
        }
    });
});

setToken.js setToken.js

export default (token) => {
    console.log("::: setToken :::");
    localStorage.setItem("cognitoToken", token);
};

congrats.pug congrats.pug

extends layout

block scripts
    script
        |   var setToken = #{setToken};
        |   setToken(#{token})

block content
    ...

layout.pug includes a client-side JS script which also has a function storeToken . layout.pug包含一个客户端JS脚本,该脚本还具有一个功能storeToken I have attempted to call that as well but nothing . 我也曾尝试称呼它,但什么也没有。

Nothing is output to the console and nothing is set in localStorage . 什么都没有输出到控制台,在localStorage什么也没有设置。 I am unsure if this is the best way to even achieve this but it appears my JS is not even being executed. 我不确定这是否是实现此目标的最佳方法,但是看来我的JS甚至没有被执行。

Is it also best practice to pass this function reference through when rendering the template or to include it on the client? 渲染模板或将其包含在客户端上时,传递此功能引用也是最佳实践吗?

EDIT 编辑

When looking in the markup, I can see that my JS is rendering correctly within the <script> of my template: 当查看标记时,我可以看到我的JS在模板的<script>中正确呈现:

<script>
    console.log("token: ", **token value**);
    var setToken = function (token) {
        console.log(&quot;::: setToken :::&quot;);
        localStorage.setItem(&quot;cognitoToken&quot;, token);
    };
    setToken(**token value**)
</script>

EDIT 2 编辑2

I have 4 pug pages that I load sequentially depending on the stage the user is at registering for Cognito. 根据用户在注册Cognito的阶段,我会依次加载4个哈巴狗页面。 I have tested injecting JS into the other 3 templates and all of that code works fine. 我已经测试过将JS注入其他3个模板中,并且所有这些代码都能正常工作。 For example: 例如:

block scripts
    script(type="text/javascript")
        |   var page = "confirm";

I can then call page in the console which prints out "confirm". 然后,我可以在控制台中调用page ,该page打印出“确认”。 I try the same variable declaration in my congrats.pug and returns undefined. 我在congrats.pug中尝试相同的变量声明,并返回未定义。 So, I imagine, this has something to do with how I render the pages. 因此,我想这与我渲染页面的方式有关。 Here's the comparison of 1 that works and the 1 that doesn't. 这是1个有效和1个无效的比较。 I cannot see any difference here (extension of users.js ) : 我在这里看不到任何区别users.js的扩展名)

/*
 * Works
 */
router.post("/confirm", (req, res, next) => {
    const { confirm } = req.body;

    cognitoUser.confirmRegistration(confirm, true, function(err, result) {
        if (err) {
            next(err);
        }
        res.render("signin", {
            title: "Signin"
        });
    });
});
//////////

/*
 * Doesn't work
 */
router.post("/signin", (req, res) => {
    const { username, password } = req.body;
    const authenticationData = {
        Username: username,
        Password: password
    };
    const authenticationDetails = new AuthenticationDetails(authenticationData);

    cognitoUser.authenticateUser(authenticationDetails, {
        onSuccess: function(result) {
            res.render("congrats", {
                title: "Congrats",
                token: result.getAccessToken().getJwtToken(),
                setToken: setToken
            });
        },
        onFailure: function(err) {
            next(err);
        }
    });
});
//////////

In the end, for some reason it was the fact that I passed a function reference to my template the way I did. 最后,由于某种原因,事实是我以这种方式将函数引用传递给模板。 If I take that out, JS worked as it should. 如果我将其删除,则JS可以正常工作。

Setting the token, I decided it was too much overhead & added complication to call a function in an external file so just did it directly within a <script> tag within the template. 设置令牌后,我认为这是过多的开销,并且增加了复杂性,无法在外部文件中调用函数,因此直接在模板的<script>标记内进行操作即可。 Here is my resulting working template: 这是我生成的工作模板:

extends layout

block scripts
    script(type="text/javascript").
        var token = "#{token}";
        localStorage.setItem("cognitoToken", token);

block content
    .container
        .col-md-6.mx-auto.text-center
            .header-title
            h1.wv-heading--title= title
        .row
            .col-md-4.mx-auto
                p You have successfully authenticated with AWS Cognito, your access token is
                    strong #{token}

Credit to this answer which showed me how to reference a pug param within a <script> tag 归功于这个答案该答案向我展示了如何在<script>标记内引用帕格参数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM