Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass variable to ejs file from express.js post request

After submitting a form I want to render the same page but with a 'message sent successfully' message above the form. With this code I get 'reference error, msg not defined', which I find strange as when I use the same code but in the GET request it works perfectly. Is there a different technique between GET and POST requests?

const express = require('express');
const app = express();
app.set('view engine', 'ejs');

app.get('/contact', (req, res) => {
    res.render('contact');
});

app.post('/send', (req, res) => {
    res.render('contact', {msg: 'Message sent successfully!'});
});
<section class="section-b">
                <div>
                    <p><%= msg %></p>
                    <form action="send" id="contact-form" method="POST">
                        <input type="text" name="name" placeholder="Name">
                        <input type="email" name="emailContact" placeholder="E-mail"><br>
                        <textarea name="message" id="message" rows="10" placeholder="Your message here..."></textarea><br>
                        <button type="submit">Submit</button>
                    </form>
                </div>
 </section>
like image 745
George Cooper Avatar asked Aug 23 '26 16:08

George Cooper


2 Answers

You need to check if the variable (msg) is defined, in the .get("/contact") request you are not sending the msg as a parameter, so that's why you are getting the error

 <% if(typeof msg !== 'undefined') { %>
    <p><%= msg %></p>
 <% } %>
like image 61
Chiller Avatar answered Aug 26 '26 05:08

Chiller


Conclusion based on @Chiller answer, if you don't want to use <% if(typeof msg !== 'undefined') { %> you need to define msg variable in the .get method, for example:

app.get('/contact', (req, res) => {
    res.render('contact', {msg: '')};
});

app.post('/send', (req, res) => {
    res.render('contact', {msg: 'Message sent successfully!'});
});

then, you can use <p><%= msg %></p> in your .ejs file without checking if variable is undefined.

But I prefer @Chiller answer as well.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!