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

У меня в папке представлений два ejs. Я создал очень простые ejs, чтобы посмотреть, могу ли я отправить переменную из одного ejs в другой ejs.

a.ejs в файле veiws

<form name="input" action="\home" method="post">
      <input type='checkbox' checked>Cheese
    <input type="submit" value="Submit" href="validation.ejs">
    </form>

b.ejs имеет

<h1><% post my variable here%></h1>

в моем узле js, это то, что я сделал const express = require ('express');const bodyParser = require ('body-parser');

const app = express();

app.use(bodyParser.urlencoded({ extended: false }));

app.set('view engine', 'ejs');

app.get('/', (req, res) => {
    res.render('index', { title: 'EJS Demo' });
});

app.post('/', (req, res) => {
    const a = req.body.a;
    res.get('index2',a);
});

app.listen(3000, () => {
    console.log('Listening....');
});

я думаю, что пост должен что-то здесь делать ...

1 Ответ

0 голосов
/ 20 ноября 2018

Я думаю, вам нужно отправить значение из form1 на странице 1 и передать эту переменную на страницу page2

, если это так, вы можете сделать это следующим образом

const express = require('express'); 
const bodyParser = require('body-parser');

const app = express();

app.use(bodyParser.urlencoded({ extended: false }));

app.set('view engine', 'ejs');


// send the page1 to the user
app.get('/', (req, res) => {
    res.render('page1', { title: 'EJS Demo' });
});


//capture the submit from the user and then send another page
//to the user
app.post('/submitForm', (req, res) => {
    const a = req.body.valueFromA;
    res.render('page2',a);
});

app.listen(3000, () => {
    console.log('Listening....');
});
<form name="input" action="\home" method="post">
      <input type='checkbox' checked>Cheese
    <input type="submit" value="Submit" href="validation.ejs">
</form>

<!-- page1 form1 -->

<html>
<head>
  <title> <& title &> </title>
</head>
  <form action='/submitForm' method='post'>
    <input type='text' value='' name='valueFromA' />
    <input type='submit' />
  </form>
</html>


<!-- page2 ejs -->

<html>
  <body>
    <p> <% value %> </p>
  </body>
</html>

b.ejs has

<h1><% post my variable here%></h1>
in my node js this is what i did const
...