簡體   English   中英

樣式和javascript文件不適用於在Node.js中提供HTML的頁面

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

我目前正在提供引用style.css和index.js的HTML頁面,但是,即使我明確聲明如果'req'請求包含這些文件,這些文件也不會應用於HTML頁面?

我的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標頭可以告訴Web瀏覽器如何解釋其接收的文件。 您的服務器代碼始終將其設置為“ text / html”,對於CSS,應將其設置為“ text / css”,對於js文件,應將其設置為“ text / javascript”。

res.write會將文件內容附加到響應中。 由於對每個請求都執行res.write(index) ,因此將在同一文件中的CSS / js之前發送HTML。 像對CSS / JS那樣嘗試對HTML使用條件

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM