简体   繁体   English

如何将变量从 Node JS 传递到前端 JS

[英]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.我正在尝试将变量从我的 NodeJS 后端传递到 JS 脚本,但到目前为止没有成功。 The backend code looks something like this:后端代码如下所示:

app.js应用程序.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.其中 Orders 是 MySQL 数据的多维数组。

On the frontend I have tried different AJAX calls, but the variables from app.js do not get saved.在前端,我尝试了不同的 AJAX 调用,但来自 app.js 的变量没有得到保存。 They do get passed through to the main.ejs file, though.不过,它们确实会传递到 main.ejs 文件。

Any advice is appreciated, this is my first NodeJS project:)任何建议表示赞赏,这是我的第一个 NodeJS 项目:)

EDIT: This is what the db-related code looks like (it works):编辑:这就是与 db 相关的代码的样子(它有效):

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:在 Node.js 中:

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

In EJS:在 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由于您使用的是 ejs,我认为您应该能够在前端做这样的事情

<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?这里还有一个类似的问题和一些建议 - Passing an object to client in node/express + ejs?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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