我正在尝试在PugJS中创建一个可点击的按钮(执行节点JS中的js)。
视图/index.pug
doctype html
html
head
title #{title}
link(rel='stylesheet', href='/css/style.css')
meta(name="viewport" content="width=device-width, initial-scale=1")
body
main
block header
header.header
h1 #{title}
block content
button(type='submit' onClick='foo();') Clickindex.js
var http = require('http'),
fs = require('fs'),
util = require('util'),
express = require('express'),
pug = require('pug');
var app = express();
app.set('view engine', 'pug');
var foo = function() {
console.log("foobar");
};
app.get('/', (req, res) => {
res.render('index', {title: "Awesome name", func: foo});
});
app.post('/', function(req, res) {
console.log(req.body);
res.send(200);
// sending a response does not pause the function
foo();
});
app.use(express.static(__dirname + '/public'));
const server = app.listen(7000, () => {
console.log(`Express running → PORT ${server.address().port}`);
});直接引用foo只会导致“未定义”,因为该函数在作用域中未定义。如果我在index.pug中通过"#{func}“引用"func”,我也会得到错误。如何从PugJS中创建的按钮引用NodeJS中的javascript函数?
发布于 2020-07-03 15:47:57
您不能使用模板引擎在服务器上执行代码,这本身就是一个巨大的安全风险,模板引擎的目的是呈现数据服务器端,因此在您的情况下,foo()函数必须执行一些操作,并在呈现结果(数据)的时刻将结果(数据)传递给pug模板例如: res.render("mytemplate",{foodataL:data})
https://stackoverflow.com/questions/62710671
复制相似问题