当我从另一个文件调用函数时,Ejs 无法加载
基本上我想在单击按钮时运行一个函数,但是当我启动服务器并转到本地主机一次时它就可以工作,这就是在本地主机页面不加载之后应该发生的情况。 (无法连接错误)
如果我删除该功能就没有问题。如何才能让它仅在单击按钮时才工作?
非常感谢。
我的 func.js
const mongoose = require("mongoose");
const axios = require('axios');
async function func() {
//MyCodes
}
module.exports = {
func: func
}
我的 index.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<button type="button" onClick= <%= func.func() %> >Click</button>
//Other codes are independent the button
</body>
</html>
app.js 中的 res.render 代码块
var func = require('./func');
app.get("/", (req, res) => {
res.render('index', {
cName: name,
symbol: symbol,
len: finds[0].result.length,
cPrice: price,
cDate: date,
func:func
});
});
});
})
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你误会了。您无法从 html(前端)调用内部 Nodejs 函数(后端)。如果您的前端需要执行一些后端操作,例如查询 mongo,您有以下选项:
#1 客户端渲染(现代)
/products/search
,它们接收 json 并返回另一个 json,html
controller.js
# 2 服务器端渲染(遗留)
这种情况下,浏览器的ajax和js并不是严格要求的。
注意
You are misunderstanding. You cannot call an internal nodejs function(backend) from the html (frontend). If your frontend need to execute some backend operation like query to mongo, you have these options:
#1 client side rendering (Modern)
/products/search
who recieve a json and return another jsonhtml
controller.js
#2 server side rendering (Legacies)
In this case, ajax and js for browser are not strictly required.
<form>
to trigger an entire page reloadNote