当我从另一个文件调用函数时,Ejs 无法加载

发布于 2025-01-15 21:00:03 字数 1009 浏览 1 评论 0 原文

基本上我想在单击按钮时运行一个函数,但是当我启动服务器并转到本地主机一次时它就可以工作,这就是在本地主机页面不加载之后应该发生的情况。 (无法连接错误)

如果我删除该功能就没有问题。如何才能让它仅在单击按钮时才工作?

非常感谢。

我的 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
        });
    });
});
})  

Basicly I want to run a function when I clicked the button, but it works when I started the server and go to localhost one time, here's what's supposed to happen, after that localhost page doesn't load. (Unable to connect error)

If I remove the function there is no problem. How can I get it to work only when I click the button ?

Many thanks.

My func.js

const mongoose = require("mongoose");
const axios = require('axios');
async function func() {
//MyCodes
}

module.exports = {
  func: func
}

My 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>

My res.render codeblocks in app.js

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

铁轨上的流浪者 2025-01-22 21:00:03

你误会了。您无法从 html(前端)调用内部 Nodejs 函数(后端)。如果您的前端需要执行一些后端操作,例如查询 mongo,您有以下选项:

#1 客户端渲染(现代)

这是现代世界中最常用的:Ajax 和 Ajax。接口

  • 公开了一个休息端点,例如 /products/search ,它们接收 json 并返回另一个 json,
  • 此端点应该在前端的某些 js 文件上使用 javascript 来使用:

html

<html lang="en">
<head>
  <script src="./controller.js"></script>
</head>
<body>
  <button type="button" onClick="search();" >Click</button>
</body>
</html>

controller.js

function search(){
$.ajax({
  url:"./api/products/search",
  type:"POST",
  data:JSON.stringify(fooObject),
  contentType:"application/json; charset=utf-8",
  dataType:"json",
  success: function(response){
    ...
  }
})
}

https://www.researchgate.net/profile/Octavian-Dospinescu/publication/316675285/figure/fig4/AS:490411216117762@1493934553127/REST-API-integrated-with-frontend-technology-using-AJAX-and -JQuery.png

  • 注 1:controller.js 包含 javascript 浏览器不适用于后端:nodejs
  • 注2:ejs仅用于返回初始html,因此最好使用其他框架,例如:react、Angular、vue

# 2 服务器端渲染(遗留)

这种情况下,浏览器的ajax和js并不是严格要求的。

  • html 上的任何事件都应该使用
    来触发整个页面重新加载。
  • 您后端从 接收任何参数,进行一些操作,例如 mongo 查询,并使用 res 返回 html 而不是 json。在您的情况下渲染

(https://galileo.phys.virginia.edu/compfac/courses/geek-hours/web-server.png


注意

  • Ejs 用于 SSR = 服务器端渲染,因此添加 ajax 对于新手来说可能很复杂。在这种情况下,请使用选项 #2
  • 您无法在客户端(用于浏览器的 JavaScript)中使用 NodeJS 函数(用于服务器的 JavaScript)。也许某些解决方法可以做到这一点,但是不要混合使用不同的东西。

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)

This is the most used in the modern world: Ajax & Api

  • your backend exposes a rest endpoints like /products/search who recieve a json and return another json
  • this endpoints should be consumed with javascript on some js file of your frontend:

html

<html lang="en">
<head>
  <script src="./controller.js"></script>
</head>
<body>
  <button type="button" onClick="search();" >Click</button>
</body>
</html>

controller.js

function search(){
$.ajax({
  url:"./api/products/search",
  type:"POST",
  data:JSON.stringify(fooObject),
  contentType:"application/json; charset=utf-8",
  dataType:"json",
  success: function(response){
    ...
  }
})
}

https://www.researchgate.net/profile/Octavian-Dospinescu/publication/316675285/figure/fig4/AS:490411216117762@1493934553127/REST-API-integrated-with-frontend-technology-using-AJAX-and-JQuery.png

  • Note 1: controller.js contains javascript for browser not for backend : nodejs
  • Note 2: ejs is only used to return the the initial html, so it is better to use another frameworks like:react, angular, vue

#2 server side rendering (Legacies)

In this case, ajax and js for browser are not strictly required.

  • Any event on your html should use <form> to trigger an entire page reload
  • You backend receives any parameter from the , make some operations like mongo queries and returns html instead json, using res.render in your case

(https://galileo.phys.virginia.edu/compfac/courses/geek-hours/web-server.png


Note

  • Ejs is for SSR = server side rendering, so add ajax could be complex for novices. In this case, use the option #2
  • You cannot use a nodejs function (javascript for server) in the client side (javascript for browser). Maybe some workaround are able to do that but, don't mix different things.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文