样式和 javascript 文件未应用于在 Node.js 中提供 HTML 的页面

Style and javascript files not applied to page that is serving HTML in Node.js

我目前正在为我的 HTML 页面提供服务,该页面引用了 style.css 和 index.js,但是,这些文件没有应用到 HTML 页面,即使我明确表示如果 'req'?

要求,则声明将它们包括在内

我的HTML(显示夹杂物):

<!DOCTYPE html>
<html>
  <head>
      <meta charset="utf-8">
      <title>Test site</title>

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

      <script src="/index.js" charset="utf-8" defer></script>

      .
      .
      .

我的server.js代码:

var PORT = 3000;
var http = require('http');
var fs = require('fs');
var path = require('path');

//cache the files
var index = fs.readFileSync('public/index.html', 'utf8', function read(err, data) {
    if (err) {
        throw err;
    }
});
var style = fs.readFileSync('public/style.css', 'utf8', function read(err, data) {
    if (err) {
        throw err;
    }
});
var indexJS = fs.readFileSync('public/index.js', 'utf8', function read(err, data) {
    if (err) {
        throw err;
    }
});

function requestHandler(req, res){
    res.setHeader('Content-Type', 'text/html');
    res.statusCode = 200
    res.write(index);
    if(req.url === '/style.css'){
        res.write(style);
    }
    if(req.url === '/index.js'){
        res.write(indexJS);
    }
    res.end();
}

//use 3000 by default if PORT is not defined
if(!(typeof PORT !== 'undefined') || PORT === null){
    http.createServer(requestHandler).listen(PORT);
}
else{
    http.createServer(requestHandler).listen(3000);
}

看来您的想法是正确的,但在服务器代码中有几点需要注意。

设置 Content Type header 告诉网络浏览器如何解释它接收的文件。您的服务器代码始终将其设置为 'text/html',其中对于 css 应设置为 'text/css',对于您的 js 文件应设置为 'text/javascript'。

res.write 会将文件内容附加到响应中。由于每个请求都会执行 res.write(index),因此您的 HTML 在同一文件中的 css/js 之前发送。尝试对 HTML 使用条件,就像对 CSS/JS 所做的那样,例如

if(req.url === '/') {
  res.setHeader('Content-Type', 'text/html');
  res.write(index);
}