【问题标题】:Serve an HTML file including CSS提供包含 CSS 的 HTML 文件
【发布时间】:2017-08-06 17:45:32
【问题描述】:

我在一个名为 index1.html 的文件中有这段代码

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<title>Page Title</title>
</head>
<body>

<h1>My First Heading</h1>
<p>My first paragraph.</p>

<script src="./testing.js"></script>
<link rel="stylesheet" type="text/css" href="./formats.css" />

</body>
</html>

这是我的 testing.js 文件

$(document).ready(function(){
    $("p").click(function(){
        alert("The paragraph was clicked.");
    });
});

这是我的formats.css文件

body {
    color: blue;
}

p {
    color: green;
}

我正在使用此文件在本地主机上托管 html 文件。

var http = require ('http');
var fs = require('fs');
var path = require('path');
var port = '2406';

function send404Response(response){
  response.writeHead(404, {"Content_Type": "text/plain"});
  response.write("Error 404: Page not found!");
  response.end();  
}

function onRequest(request,response){
  if(request.method == 'GET' && request.url == '/'){
    response.writeHead(200, {"Content-Type": "text/html"});
    fs.createReadStream(path.join(__dirname, "index1.html")).pipe(response);

  } else{
    send404Response(response);
  }
}

http.createServer(onRequest).listen(port);
console.log("Server is now running on port 2406...");

当我在节点中运行 running.js 时,当我转到本地主机时,它不包含任何格式或 Jquery。我想知道为什么会出现这种情况以及我可以做些什么来解决它。

【问题讨论】:

  • 旁注:永远不要在body 中包含样式表。将其放入head 以避免不必要的重新渲染。

标签: javascript html css node.js server


【解决方案1】:

您的 onRequest 函数仅处理 1 个可能的 url “/”。

可以添加更多 if 语句来提供不同的文件...

function onRequest(request,response){
  if(request.method == 'GET' && request.url == '/'){
    response.writeHead(200, {"Content-Type": "text/html"});
    fs.createReadStream(path.join(__dirname, "index1.html")).pipe(response);

  } else if (request.method == 'GET' && request.url == '/formats.css'){
    response.writeHead(200, {"Content-Type": "text/css"});
    fs.createReadStream(path.join(__dirname, "formats.css")).pipe(response);

  } else if (request.method == 'GET' && request.url == '/testing.js'){
    response.writeHead(200, {"Content-Type": "text/javascript"});
    fs.createReadStream(path.join(__dirname, "testing.js")).pipe(response);

  } else {
    send404Response(response);
  }
}

但您可能想研究一下像 express 这样的 HTTP 服务器框架。

【讨论】:

    【解决方案2】:

    或者,您可以通过本地安装在根目录中使用npmhttp-server,然后可以托管您的index.html 及其依赖项。您不需要额外的代码或维护脚本来托管您的页面。

    【讨论】:

      猜你喜欢
      • 2017-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-23
      • 2016-05-17
      • 2019-05-26
      相关资源
      最近更新 更多