How to pass variables from Node JS to frontend JS

I'm trying to pass variables from my NodeJS backend to a JS script, without success so far. The backend code looks something like this:

app.js

const express = require('express');
const app = express();
const path = require('path');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');

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


port = process.env.PORT || 3000;
app.listen(port);
app.use(express.static(__dirname + '/'));

app.engine('ejs', require('ejs').renderFile);
app.use(cookieParser());

...
var Orders = (...);
app.get('/', (req,res,next) => {
        res.render("main", {Orders: Orders});
    
    });

where Orders is a multidimensional array of MySQL data.

On the frontend I have tried different AJAX calls, but the variables from app.js do not get saved. They do get passed through to the main.ejs file, though.

Any advice is appreciated, this is my first NodeJS project :)

EDIT: This is what the db-related code looks like (it works):

const mysql = require('mysql');
var con = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '12345678',
    database: 'DBName'
    });
    
    con.connect(function(err) {
    if (err) 
    {console.log("error");
    throw err;}
    console.log("Connected!");
    });
 // Get earlier orders for that store
    con.query("SELECT employee_id, datum, time_hour, time_minute, duration, treatment FROM orders WHERE  store_id = *store_id*", function (err, result, fields) {
    if (err){throw err};
    Orders = result;
    });

Upvotes: 3

Views: 3429

Answers (2)

Enoch Chejieh
Enoch Chejieh

Reputation: 136

In Node.js:

app.get('/', (req,res,next) => {
    res.render("main", {Orders: Orders});
});

In EJS:

<script type='text/javascript'>
    var orders = <%-JSON.stringify(Orders)%>
</script>

Upvotes: 2

Kingsley Solomon
Kingsley Solomon

Reputation: 480

Since you are using ejs, I think you should be able to do something like this on the frontend

<script>
   var Orders = <%- JSON.stringify(Orders || null) %>
</script>

Here's also a similar question with some suggestions - Passing an object to client in node/express + ejs?

Upvotes: 1

Related Questions