Передать переменную js узла в шаблон ejs - PullRequest
0 голосов
/ 06 июня 2018

У меня есть почтовый запрос в файле js узла "index.js"

this.app.post('/profile', (req, res) => {                        
            let password = req.body.password;            
            let newWallet = operator.createWalletFromPassword(password);
            let projectedWallet = projectWallet(newWallet);
            res.render('profile.ejs', {
                user : req.user,
            });
            console.log(JSON.stringify(projectedWallet));        
        });

И в файле profile.ejs, который нужно показать клиенту, я вижу: ЭТО ПОЛНЫЙ КОД, КОТОРЫЙ Я ПРОСТО РЕДАКТИРУЮ, КАК ЗАПРОСИЛ.

<html lang="en">
<head>
    <title>Node Authentication</title>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css">
    <style>
        body        { padding-top:80px; word-wrap:break-word; }
    </style>
</head>
<br>
   <%- include header %>

   <div class="container">

    <div class="page-header text-center">
        <h1><span class="fa fa-anchor"></span> Profile Page</h1>
        <a href="/logout" class="btn btn-default btn-sm">Logout</a>
        <form action="/profile" method="get">
            <button type="submit" class="btn btn-warning btn-lg" id="sub" >test</button>
        </form> 
    </div>

    <div class="row">

        <!-- LOCAL INFORMATION -->
        <div class="col-sm-6">
            <div class="well">
                <h3><span class="fa fa-user"></span> Local</h3>
                    <form action="/profile" method="post">
                        <p>                                                    
                            <strong>id</strong>: <%= user.id %><br>
                            <strong>username</strong>: <%= user.username %><br>
                            <strong>password</strong>: <%= user.password %>

                        </p>                                               
                        <textarea id="myTextArea" cols=50 rows=10><%= data %>
                        </textarea>
                        <!-- these fields will be sent to server -->
                        <input type="hidden" name="username" value="<%= user.username %>">
                        <input type="hidden" name="password" value="<%= user.password %>">
                        <button type="submit" class="btn btn-warning btn-lg" id="sub" >Wallet</button>
                    </form>


            </div>
        </div>

    </div>

</div>
    <%- include footer %>

Я хочу добавить значение "projectedWallet" в пост-запросе к textarea в файле ejs, но я не знаю, как это сделать.

Ответы [ 3 ]

0 голосов
/ 06 июня 2018

вы можете сохранить переменную в локальных переменных ответа и затем использовать ее на стороне внешнего интерфейса (в данном случае EJ).

обновленный код ::

index.js

this.app.post('/profile', (req, res) => {                        
            let password = req.body.password;            
            let newWallet = operator.createWalletFromPassword(password);
            let projectedWallet = projectWallet(newWallet);
            //added line
            res.locals.projectedWallet =  projectedWallet
            res.render('profile.ejs', {
                user : req.user,
            });
            console.log(JSON.stringify(projectedWallet));        
        });

profile.ejs

<form action="/profile" method="post">
    <p>                                                    
        <strong>id</strong>: <%= user.id %><br>
        <strong>username</strong>: <%= user.username %><br>
        <strong>password</strong>: <%= user.password %>                         
    </p>   
      <!-- updated line -->                                  
    <textarea id="myTextArea" cols=50 rows=10><%=projectedWallet %>
    </textarea>
    <!-- these fields will be sent to server -->
    <input type="hidden" name="username" value="<%= user.username %>">
    <input type="hidden" name="password" value="<%= user.password %>">
    <button type="submit" class="btn btn-warning btn-lg">Wallet</button>
</form>
0 голосов
/ 12 января 2019

Вы должны проверить, определена ли переменная ( projectedWallet ), в запросе .get вы не отправляете projectedWallet в качестве параметра, поэтому вы получаетеошибка

<% if(typeof projectedWallet !== 'undefined') { %>
   <p><%= projectedWallet %></p>
<% } %>

Если вы визуализируете представление несколько раз, иногда с переменными, а другие без, вам необходимо добавить условие и проверить, существует ли эта переменная для каждого рендера

0 голосов
/ 06 июня 2018

Вы захотите ввести projectedWallet в текстовое поле через EJS следующим образом:

index.js

this.app.post('/profile', (req, res) => {                        
  let password = req.body.password;            
  let newWallet = operator.createWalletFromPassword(password);
  let projectedWallet = projectWallet(newWallet);
  res.render('profile.ejs', {
    user : req.user,

    // We are now feeding your EJS template another variable
    projectedWallet : JSON.stringify(projectedWallet),
  });
  console.log(JSON.stringify(projectedWallet));        
});

... и используйте его в текстовой области внутри вашего шаблона

profile.ejs

<form action="/profile" method="post">
  <p>                                                    
   <strong>id</strong>: <%= user.id %><br>
   <strong>username</strong>: <%= user.username %><br>
   <strong>password</strong>: <%= user.password %>                         
  </p>                                               
  <textarea id="myTextArea" cols=50 rows=10>

    <!-- We now populate the template with the sent variable -->
    <%= projectedWallet %>

  </textarea>
  <!-- these fields will be sent to server -->
  <input type="hidden" name="username" value="<%= user.username %>">
  <input type="hidden" name="password" value="<%= user.password %>">
  <button type="submit" class="btn btn-warning btn-lg">Wallet</button>
 </form>
...