【问题标题】:How can I send the value from Node to HTML for processing in JavaScript?如何将值从 Node 发送到 HTML 以在 JavaScript 中处理?
【发布时间】:2020-01-11 06:14:10
【问题描述】:

能否在 HTML 中获取 Node 值作为 JavaScript 参数(Node code value -> JavaScript inside index.html)?

我找不到办法。

app.js

const express = require('express');
const app = express();
const idxRouter = require('./router/index.js');

app.use('/',idxRouter);

index.js

const express = require('express'); //node express framework
const router = express.Router();
var fs = require('fs');
const db = require('../dbconfig/db');
const num = 2;
router.get('/',function(req,res){
    function test(num) {
        try {
            db.query('SELECT a.explain from explain a  where no =' + num, function (err, rows) {
                if (err) {
                    console.log(err);
                }
                console.log(rows);
            });
        } catch (e) {
            console.log(e);
        }
    };
    test(num);
    res.end(fs.readFileSync( '/Users/hoon/node/drawio/src/main/webapp/index.html'));
});//app.get '/' end

module.exports = router;

【问题讨论】:

  • 到目前为止你尝试了什么?请提供一些代码示例。我想你使用expressjs?如果是这样,您使用哪个模板引擎?
  • 我很着急。该文件已被修改。谢谢你的回复
  • 你试过我的解决方案了吗?我可以尽快对其进行编辑,因此它符合您的需求。
  • 谢谢,但我还没有应用解决方案。我会尝试发表评论。
  • 我调整了我的解决方案以适应您的用例。如果有帮助,请尝试一下并将我的回答标记为已接受。

标签: javascript html node.js


【解决方案1】:

这应该可行:

/router/index.js

const express = require('express'); //node express framework
const router = express.Router();
var fs = require('fs');
const db = require('../dbconfig/db');
const num = 2;

router.get('/', function (req, res) {
    function test(num) {
        try {
            db.query('SELECT a.explain from explain a  where no =' + num, function (err, rows) {
                if (err) {
                    console.log(err);
                }
                return rows;
                console.log(rows);
            });
        } catch (e) {
            console.log(e);
        }

    };
    res.render('index.html', {
        rows: test(num)
    });
});

module.exports = router;

app.js

const express = require('express');
const app = express();
var nunjucks = require('nunjucks');
const idxRouter = require('./router/index.js');

app.use('/',idxRouter);

nunjucks.configure('views', {
    autoescape: true,
    express: app
});

app.listen(3000);

/views/index.html

<!doctype html>
<html>

<head>
    <title>My App</title>
</head>

<body>
    <ol>
        {% for row in rows %}
          <!--replace .name with your column/key you want to show -->
        <li>{{ row.name }}</li> 
        {% endfor %}
    </ol>
</body>

</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多