简体   繁体   中英

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

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>

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM