我在使用javascript加载我的index.html文件时遇到了麻烦(我很确定这可能是在javascript中最容易做的第五件事)。
我会尽量保持简短;基本上,当我手动打开index.html时,使用CSS可以很好地对其进行加载(如下图所示)
http://i.stack.imgur.com/VZfbq.png
但是,当我使用javascript加载它时,它仅加载具有默认格式的纯html,而没有我的CSS:
http://i.stack.imgur.com/Eovav.png
这些文件位于以下位置:
server.js位于:根目录
index.html在:根/公共
style.css位于:root / public / css
server.js
var http = require('http');
var fs = require('fs');
var handleRequest = function handleRequest(request, response){
if (request.url==='/index.html' || request.url==='/') {
response.writeHeader(200, {'Content-type':'text/html'});
fs.readFile('./public/index.html', function (err, file) {
if (err) throw err;
response.end(file);
});
} else {
response.writeHeader(404);
response.end('Are you lost friend?');
}
}
var server = http.createServer(handleRequest);
var PORT = 8080;
server.listen(PORT, function(){
console.log("Server listening on: http://localhost:%s", PORT);
});
index.html
<!DOCTYPE html>
<html>
<head>
<title>My not-so-amazing Webpage</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<h1>The Inspiratorator v5.7.0</h1>
<p>I AM THE SUN</p>
</body>
</html>
style.css
h1 {
background-color: #000000;
color: rgba(255, 255, 255, 1);
backface-visibility: 0.5;
font-size: 50px;
text-align: center;
}
p {
background-color: blue;
font-family: sans-serif;
color: white;
}
看一下您如何处理请求,基本上您是拒绝除之外的每个请求/
。浏览器无法访问css文件。
if (request.url==='/index.html' || request.url==='/') {
response.writeHeader(200, {'Content-type':'text/html'});
fs.readFile('./public/index.html', function (err, file) {
if (err) throw err;
response.end(file);
});
} else {
response.writeHeader(404);
response.end('Are you lost friend?');
}
在这里,我为css文件添加了一个例外,它可以正常工作。
笔记:
您应该更改此代码以满足您的需求,请勿在生产中使用。
} else if (request.url.indexOf('css') != -1) {
response.writeHeader(200, {'Content-type':'text/css'});
fs.readFile('./public/css/style.css', function (err, file) {
if (err) throw err;
response.end(file);
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句