How do I send variables from Express to a dynamic page

989 views Asked by At

I've recently switched from XAMPP/LAMP stack to MEAN stack and oh dear, these new things are amazing but I can't wrap my head around this.

In a LAMP stack, if you want to display some variable (like your username from a Database or some dynamic variable like that) you'd do something like this:

index.php

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <?php echo $some_var; ?>
  </body>
</html>

and that's it. At the start of the file, you can pass the data from a Database to the variable and that would be it.

I don't understand how you achieve this in a MEAN stack.

Do I have to use a Template engine like EJS/Pug? If I understand it, I'd do back-end in the same file that Express is (like for example, selecting data from databases) and then I'd do something like this:

app.js

app.set("views", "./views");
app.set("view engine", "pug");
app.get("/", (req, res) => {
   res.render("index", {message:"Hi"});
});

Is that how you send data from server→client in a production/deploy environment? Is there a more practical solution to it? Given that pug code is way too different from HTML (for example). Thanks and sorry for my english.

1

There are 1 answers

3
fh0592x On BEST ANSWER

In a MEAN stack, you would use Express as the backend API and pass JSON data to the frontend, which could be Angular, React, Vue, etc.

For templating with Express, this should get you started. Let us know if this helps :)