【问题标题】:Jquery on client side with nodejs server带有nodejs服务器的客户端Jquery
【发布时间】: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>

【问题讨论】:

    标签: javascript html jquery node.js express


    【解决方案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 当然,您可以提供前端文件夹中的所有静态文件,但我认为您不应该提供模板文件或包含逻辑的文件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-19
    • 1970-01-01
    • 2018-07-09
    • 2012-04-06
    • 2019-01-29
    相关资源
    最近更新 更多