基本上我想在單擊按鈕時運行一個函式,但是當我啟動服務器并轉到 localhost 一次時它可以作業,這就是應該發生的事情,在該 localhost 頁面沒有加載之后。(無法連接錯誤)
如果我洗掉該功能,則沒有問題。只有當我單擊按鈕時,我才能讓它作業?
非常感謝。
我的 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
});
});
});
})
uj5u.com熱心網友回復:
你誤會了。您不能從 html(前端)呼叫內部 nodejs 函式(后端)。如果您的前端需要執行一些后端操作,例如查詢 mongo,您有以下選項:
#1 客戶端渲染(現代)
這是現代世界最常用的:Ajax & Api
- 你的后端暴露了一個休息端點,比如
/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>
控制器.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){
...
}
})
}

- 注 1:controller.js 包含瀏覽器的 javascript,而不是后端:nodejs
- 注2:ejs只用于回傳初始html,所以最好使用其他框架,如: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

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.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/447599.html
下一篇:Node.jswebpack5錯誤,找不到模塊;重大變化:webpack<5用于包含node.js核心的polyfill
