简体   繁体   English

Jquery 在客户端与 nodejs 服务器

[英]Jquery on client side with nodejs server

I use nodejs (in a docker-compose container, not sure if that is relevant) to set up a local web app.我使用 nodejs(在 docker-compose 容器中,不确定是否相关)来设置本地 web 应用程序。 I would like to use jquery on the client-side to load an HTML file into a div.我想在客户端使用 jquery 将 HTML 文件加载到 div 中。 Unfortunately, it is not working.不幸的是,它不起作用。 The initial index.html and the new.html are in the same folder (/frontend/).初始索引.html 和新的.html 位于同一文件夹(/frontend/)中。 What am I missing?我错过了什么?

Nodejs app: 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:索引.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>

Lastly the HTML I want to import new.html:最后是 HTML 我要导入 new.html:

<HTML>
  <head>
  </head>
  <body>
    <p>This is demo text.<p>
  </body>
</html>

Simply use express.static() to serve static HTML files只需使用express.static()即可提供 static HTML 文件

const app = express();

app.use(express.static("frontend"))

app.listen(3000, function(){
    console.log('Example app listening on port 3000!');
});

If you're just after a plain old static file server, you might find serve simpler...如果您只是在使用普通的旧 static 文件服务器,您可能会发现服务更简单......

npx serve frontend

Basically the new.html file is not served.基本上不提供 new.html 文件。

You need use the following code to serve public files in a directory named public .您需要使用以下代码在名为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!');
});

Ref: https://expressjs.com/en/starter/static-files.html参考: https://expressjs.com/en/starter/static-files.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM