![](/img/trans.png)
[英]Automatic reference of local *.js and *.css files into index.html with grunt
[英]Why are the local .css files and .js file not linked to the index.html file?
我正在使用node.js並嘗試發送包含以下標記的.html文件:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="description" content="This is my personal profile website" />
<link rel="stylesheet" type="text/css" href="profile_design.css" />
<link rel="stylesheet" href="jquery.fancybox-1.3.4/fancybox/jquery.fancybox-1.3.4.css" type="text/css" media="screen" />
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="jquery.fancybox-1.3.4/fancybox/jquery.fancybox-1.3.4.pack.js"></script>
<script type="text/javascript" src="profile.js"></script>
這是node.js中的HTTP服務器:
var fs = require('fs');
var http = require ('http');
http.createServer(function (request, response) {
console.log('request starting...');
fs.readFile('C:/Users/.../index.html', function(error, content) {
if (error) {
response.writeHead(500);
response.end();
} else {
//response.writeHead(200, { 'Content-Type': 'text/html' });
response.end(content, 'utf-8');
}
console.log(error);
});
}).listen(8080);
問題在於index.html文件以良好的方式返回,但是所有JavaScript文件和CSS均未正確發送到客戶端。 問題是如何發送那些.js和.css文件?
我遇到了同樣的問題,但是在了解幕后情況之前,我不想使用任何外部模塊或框架。 因此,這就是我自己解決CSS文件問題的方法。 希望它對某人有用。
每當我請求/style.css
我都會調用此簡單函數:
function style(response) {
console.log("Request handler 'style' was called.");
fs.readFile("style.css", function(error, file) {
if(error) {
response.writeHead(500, {"Content-Type": "text/plain"});
response.write(error + "\n");
response.end();
} else {
response.writeHead(200, {"Content-Type": "text/css"});
response.write(file);
response.end();
}
});
}
基本上,我們讀取靜態文件,然后根據要求將其發送回去。 請注意,您必須注意路由請求。
瀏覽器嘗試通過node.js服務器的端口8080獲取.css和.js資源文件。 但是,無論請求是什么,您的服務器都不會提供任何服務,但只能提供index.html文件。
建議:使用express.js插件並設置更復雜的路由 。
您需要有一個處理程序來處理諸如node-paperboy或node-static之類的資產,或者使您自己的資產。
我不確定這是否回答了您的問題,但就我而言,我將所有的css和js文件添加到了view文件夾中,然后在server.js中添加了以下內容
server.use(express.static(__目錄名+ '/視圖/'));
這為我解決了這個問題
解決此問題的簡單方法是,在html文檔(index.html)的末尾,即body標記之前,添加style.css代碼。 在我看來,這確實有效。 只需添加:
<style type="text/css"> "your css code goes here" </style>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.