带有nodejs服务器的客户端Jquery
Posted
技术标签:
【中文标题】带有nodejs服务器的客户端Jquery【英文标题】:Jquery on client side with nodejs server 【发布时间】:2022-01-16 14:25:09 【问题描述】:我使用 nodejs(在 docker-compose 容器中,不确定是否相关)来设置本地 Web 应用程序。我想在客户端使用 jquery 将 html 文件加载到 div 中。不幸的是,它不起作用。初始 index.html 和 new.html 位于同一文件夹 (/frontend/) 中。我错过了什么?
Nodejs 应用:
var app = express();
// home route returns rendered html content
app.get("/", (req, res) =>
res.sendFile(__dirname + "/frontend/index.html");
);
app.listen(3000, function()
console.log('Example app listening on port 3000!');
);
index.html:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous">
</script>
<script type="text/javascript">
$(document).ready(function()
$("#imported").load("new.html");
);
</script>
</head>
<body>
<div> This is content of the index HTML and below is the imported HTML:</div>
<div id="imported"></div>
</body>
</html>
最后是我要导入new.html的HTML:
<HTML>
<head>
</head>
<body>
<p>This is demo text.<p>
</body>
</html>
【问题讨论】:
【参考方案1】:只需使用express.static()
到serve static HTML files
const app = express();
app.use(express.static("frontend"))
app.listen(3000, function()
console.log('Example app listening on port 3000!');
);
如果您只是在使用普通的旧静态文件服务器,您可能会发现 serve 更简单...
npx serve frontend
【讨论】:
感谢@Phil,这正是我所需要的,我仍然是一个巨大的 nodejs 菜鸟:/ @Tobi 不客气。仅供参考,这更像是 ExpressJS 的事情; node 只是 JS 运行时 嗯,对,我只是使用 express,因为我看到的第一个教程使用了它:D 再次感谢! @Tobi 如果您只是在使用普通的旧静态文件服务器,您可能会发现serve 更简单 好的,我会调查的。是的,与此同时它将是静态的。但是,也许它会在以后发展以包含更多逻辑。干杯!【参考方案2】:基本上不提供new.html文件。
您需要使用以下代码在名为 public
的目录中提供公共文件。
var app = express();
// Put new.html into public folder.
// /public/new.html
// /frontend/index.html
app.use(express.static('public'))
// home route returns rendered html content
app.get("/", (req, res) =>
res.sendFile(__dirname + "/frontend/index.html");
);
app.listen(3000, function()
console.log('Example app listening on port 3000!');
);
参考:https://expressjs.com/en/starter/static-files.html
【讨论】:
为什么不只提供“前端”文件夹中的所有静态文件?为什么要移动文件? @Phil 当然,您可以提供前端文件夹中的所有静态文件,但我认为您不应该提供模板文件或包含逻辑的文件。以上是关于带有nodejs服务器的客户端Jquery的主要内容,如果未能解决你的问题,请参考以下文章
带有 Einaros WebSocket 的 NodeJS:客户端 Ping 服务器 VS 服务器 Ping 客户端
Websockets:从NodeJS websocket服务器到带有WebSocketSharp的C#客户端的多个响应
需要带有 Nodejs 示例的 RESTful MongoDB
如何告诉我的 NodeJS 服务器在带有两个按钮的 HTTP 表单中单击了哪个按钮?