3

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;
    });

2 Answers2

2

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>
Enoch Chejieh
  • 136
  • 1
  • 4
1

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?

Kingsley Solomon
  • 481
  • 1
  • 4
  • 9
  • Thanks! This does indeed work when I just put that at the bottom of the body of the ejs file, however it does not when I try to add the code to the external js file. Also, having this code in the ejs file does still not make them available for the js file. – Ole Hylland Spjeldnæs Jun 27 '20 at 16:39
  • I guess one solution would be to just add all my frontend js to the ejs file, rather than having a separate file. Somewhat untidy, but oh well – Ole Hylland Spjeldnæs Jun 27 '20 at 16:41
  • 1
    Yeah, that can be untidy. Does it mean your external js file was included at the top of this page i.e before this script tag? I want to believe 'var' should define this value in the global context. Try using 'window.Orders' instead of 'var', I doubt there'd be any difference. – Kingsley Solomon Jun 28 '20 at 17:15
  • The relative placement of the relative file doesn't affect anything. Thanks, I'll try it when I get back on my computer! – Ole Hylland Spjeldnæs Jun 29 '20 at 21:15