我是 Javascript 和 Nodejs 新手,我不知道如何最好地组织事物。我正在为 C++ 应用程序编写一个 Web 界面,方法是使用 Nodejs 和 V8 转换来包装 C++ API。我的问题是,有什么方法可以使用 Express 来提供对 Nodejs 内部的函数/全局引用的 HTML 服务吗?或者我是否必须在 HTML 中使用一堆 res.write(html) 类型的调用才能做到这一点?
例如,我想使用从 C++ 配置 API 访问的内容预填充表单数据。 C++ API 封装在 Nodejs 模块中。现在,任何需要动态生成的东西(比如预填表格)我都会做类似的事情,
var novaconfig = require('./NodeAppConfig/build/Release/appconfig');
var AppConfiguration = new Appconfig.AppConfigBinding();
var express=require('express');
var app = express.createServer(express_options);
app.configure(function () {
app.use(express.methodOverride());
app.use(express.bodyParser());
app.use(app.router);
});
app.get('/configureApplication.html', function(req, res) {
console.log("[200] " + req.method + " to " + req.url);
res.writeHead(200, "OK", {'Content-Type': 'text/html'});
res.write('<HTML>');
res.write('<HEAD>');
res.write(' <link rel="stylesheet" type="text/css" href="configstyle.css" media="screen">');
res.write('</HEAD>');
res.write('<BODY>');
res.write('<label>');
res.write(Interface);
res.write('</label>');
res.write('<form method="post" action="/configureNovaSave">');
res.write('<input type="text" name="interface" value="');
res.write(AppConfiguration.GetCurrentInterface());
res.write('" /><br />');
res.write('<input type="submit" name="submitbutton" id="submitbutton" value="Save Settings" />');
res.write('</form>');
res.write("<br/>");
res.write('</BODY>');
res.write('</HTML>');
res.end();
});
但这显然是一个糟糕的方法。有没有办法将动态生成的 HTML 放在独立文件中,然后仍然在其中访问 AppConfiguration.GetCurrentInterface() ?组织此类文件的好方法是什么?
最佳答案
我认为你想要的是一个模板引擎。也许看看 Jade 或 Mustache。然后,您只需传入您想要动态的部分,引擎就会为您呈现页面。
关于javascript - 访问expressJs静态HTML中的nodejs函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10217569/