html - 使用 Node 服务器时,css js 不链接到链接的 html 文件

标签 html node.js

我正在尝试使用 Node js 服务器提供 .css .js 等静态文件。 index.html 文件得到服务,链接的 css 和 js 也被加载。

现在我在index.html 文件中有一个div,我将另一个名为login.html 的html 文件的内容加载到其中。 这个login.html 文件有一个链接到它的css 和一个js 文件。 login.html 本身使用 jquery 函数 load() 加载,这意味着它可以被服务器访问。但是,由于文件路径错误,链接到 login.html 的 css 和 js 未加载。

这是文件夹结构see this image

以下是index.html的主要部分

<!DOCTYPE html>
<html>
    <head>
        <title>Anything</title>
        <link href="./index/index.css" type="text/css" rel="stylesheet">  //These files
        <script src="./Resources/jquery/jquery-3.2.1.js"></script>        //get loaded
        <script src="./index/index.js"></script>                          //by the server
    </head>
    <body>
        <div class="content"></div>     // I am trying to load login.html here
    </body>
</html>

这是jquery函数

$(".user").click(function(){                       
        $(".content").load("./../pages/login/login.html");  
 });

“.user”是一个我没有在index.html中显示的div

这是登录.html

<link href="./login.css" type="text/css" rel="stylesheet">  //doesn't load
<script src="./login.js"></script>                          //doesn't load
<h2>Login is loaded</h2>

最后这是用于创建 Node js 服务器的 server.js

var express = require("express");
var app = express();
var path = require("path");

app.set('port', 8080);
app.use(express.static(path.join(__dirname, "public")));
app.use(express.static(path.join(__dirname, "login")));

var server = app.listen(app.get('port'), function() {
  var port = server.address().port;
});

console.log("Server running.");

我知道 css 和 js 文件未加载,因为我在 chrome 开发人员工具窗口中看到此错误:

GET http://localhost:8080/login.css 

结论:服务器无法加载辅助服务的html文件的css和js文件,因为请求url错误。但是,index.css 和index.js 文件会通过正确的url 加载。

目标:通过login.html页面使用此node js服务器加载login.css和login.js。

最佳答案

您需要更改 login.html 中的相对路径以匹配服务器上的相对路径,这样 ./login.css 将变为 ./../pages/login/login.css(就像您用来加载 login.html 文件的路径)

关于html - 使用 Node 服务器时,css js 不链接到链接的 html 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43558265/

相关文章:

node.js - 从 mongoDB 数组中返回随机键和单词

express.js 中的 JSON 序列化算法

html - 应用程序应该将html内容还是markdown内容保存到数据库中吗?

javascript - 如何将 Bootstrap Burger 菜单功能添加到常规 Bootstrap 菜单?

css - HTML 如何使日期选择器在 Internet Explorer 11 上可见?

javascript - lodash 类型错误没有函数 findKey()

node.js - 在 node.js 服务器上使用 supertest/superagent 读取响应输出缓冲区/流

javascript - 做服务器端编程需要多少客户端编程?

javascript - 导航栏 : position Absolute and Sticky

javascript - 如何使用 upsert :true 在 MongoDB 更新中 $cond $push/$pull