html - External CSS is not working in NodeJS
问题描述
I have external css file used by the html page in my nodeJS project. Following is my file structure
ProjectFolder
----server.js
----index.html
----style.css
My server.js file is following
var http = require('http');
var fs = require('fs');
var $ = require('jquery');
function onRequest(request, response) {
response.writeHead(200,{'Content-Type':'text/html'});
fs.readFile('./index.html',null, function (error,data) {
if(error){
response.writeHead(404);
response.write('File not found')
} else {
response.write(data);
}
response.end();
});
}
http.createServer(onRequest).listen(8081);
My html page is following
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href='style.css'>
<script src="https://ajax..."></script>
<script>
........
</script>
</head>
<body>
<div id="inputDiv">
<h1>User Details</h1>
</div>
</body>
</html>
My css file is following
div {padding-bottom: 10px}
label {float: left; width: 6em; text-align: right;padding-right: 4px}
input {text-align: left;}
textarea {alignment: right;}
When I run node server.js and access index.html, it loads the html page without css styling. But I tried opening my html page outside nodejs (just in the browser) and then I can see styles. What is the issue in my code?
解决方案
Your web server does not serve the CSS file. Try to access it manually. It won't work.
When you run your file from filesystem file:///
, the style.css can be loaded because it is in the same directory.
But when you use something like localhost/index.html
or something, the browser tries to access localhost/style.css
but the nodejs server you have above would not handle the file.
See this answer which might be a help for you.
If you want to make a practical web server use something like Express or Koa.
推荐阅读
- javascript - 根据条件更改占位符
- node.js - Runtime.ImportModuleError 错误:找不到模块“axios/lib/utils”无服务器
- javascript - jsinspect 在多个文件中查找相似代码
- python - 根据具有特定条件的上述行中的一列的值创建新行 - pandas 或 numpy
- kotlin - ProgressDialog 在方法完成后显示
- excel - 将多个 .csv 文件导入单个电子表格
- sql-server - 在 nvarchar 列上进行 FREETEXT 搜索
- excel - 我想在每次打印值时停止循环
- relational-database - 主键与候选键 - 关系 DBMS
- yaml - Helm 模板:如何在 helm 函数中引发异常?