Nodejs在没有CSS的情况下加载我的HTML

时间:2016-09-07 10:39:50

标签: html css node.js

我在nodeJS中做了一个小程序,cloud9应该启动我的html。它工作但没有CSS。我尝试了很多东西,但我没有找到解决方案。

H > 1

我的HTML:

var http = require("http");
var fs = require("fs");
var events = require('events');
var eventEmitter = new events.EventEmitter();

fs.readFile('homepage.html', function(err, data) {
  if (err) return console.log(err);

  var server = http.createServer(function (request, response) {
    response.writeHead(200, {'Content-Type': 'text/html'});
    response.writeHead(200, {'Content-Type': 'text/css'});
    response.write(data);
    response.end();
  }).listen(8081);
});

console.log("Server running.");

`

我的CSS:

<!DOCTYPE html>
<html>
<head>
   <title>My project</title>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="css/style.css"/>
</head>
<body>
    <h1>My project</h1>
    <p>coming soon</p>
</body>

我尝试在浏览器上只打开.html,而我的h1是4px。

1 个答案:

答案 0 :(得分:0)

<link rel="stylesheet" href="css/style.css"/>

您告诉浏览器加载css/style.css

浏览器会询问服务器。

response.writeHead(200, {'Content-Type': 'text/html'});

服务器说&#34;这是一些HTML!&#34;

response.writeHead(200, {'Content-Type': 'text/css'});

然后它说&#34;这是一些CSS!&#34;

这很奇怪。您可以发送HTML文档一个独立的样式表。你不能同时发送两者。

response.write(data);

然后服务器发送homepage.html

的内容

因此,当浏览器要求样式表时,它会获得主页的另一个副本。

您需要注意the request object,它会告诉您浏览器的要求。特别要注意methodurl属性。

然后,您需要为该特定网址(应该包含文件类型的正确的内容类型)给出正确的响应,如果不是,则可能是404错误。要求你期待的东西)。

目前您总是发送主页。如果浏览器要求/,则会发送主页。如果它要求/css/style.css,则发送主页。如果它要求/this/does/not/exist,则发送主页。