2017-03-15 52 views
0

我有這樣的代碼在一個名爲index1.html提供HTML文件包括CSS

<!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的,當我去到本地主機。我不知道爲什麼是這樣的話和我能做些什麼來解決它。

+0

側面說明:從來沒有包括在'body'樣式表。把它放在'head',以避免不必要的重新渲染。 – Damon

回答

0

您的onRequest函數僅處理1個可能的url「/」。

COULD添加更多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); 
    } 
} 

但你可能想看看像快遞HTTP服務器框架。

0

或者,您可以在本地安裝根目錄中使用npmhttp-server,然後能夠託管您的index.html及其依賴關係。你並不需要額外的代碼或腳本維護託管您的網頁。