簡體   English   中英

提供包含CSS的HTML文件

[英]Serve an HTML file including CSS

我在名為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。 我想知道為什么會這樣,我該如何解決。

您的onRequest函數只能處理1個可能的網址“ / ”。

可以添加更多的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服務器框架。

或者,您可以通過在本地安裝在根目錄中使用npmhttp-server ,然后能夠托管index.html及其依賴項。 您不需要額外的代碼或維護腳本來托管頁面。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM