Почему мой кодовый файл css имеет мой источник html, когда я открываю инструмент разработчика в Google chrome? - PullRequest
0 голосов
/ 07 апреля 2020

У меня возникает следующая проблема, когда я запускаю свое веб-приложение, исходный код HTML представляется в файле css в chrome инструмент разработчика:

У меня есть файл HTML называется index. html и следующим в источнике.

    <!DOCTYPE html>
    <html>
    <head>
    <title>Node</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="style.css" rel="stylesheet"  type="text/css" title="Default Styles" 
   media="screen">


 </head>

 <body>
    <h1> Welcome to my first node.js Website </h1>

    <h2> this is how you and where you do the mark up in node js</h2>





    <!-- footer -->
    <div class= "base">
        <footer>
            <nav>

            </nav>
        </footer>
    </div>


</body>
  </html>

И вот мой CSS файл называется style. css

  html, body{
  font-family: 'Open Sans', sans-serif;
  font-size: 100%;
  padding: 0;
  margin: 0;
  width: 100%;
  background: skyblue;
  color: #fff; 

  }


 /*
footer 
 */

 .base{

  height: 50px;
  width: 100%;
  background-color: black;
  border-bottom: 1px solid rgba(221, 221, 221, 0.13);
  bottom: 0%;
  position: fixed;

  }

при запуске код на локальном сервере и открытие инструмента разработчика на Google chrome Я вижу, что исходный код HTML находится в файле CSS. [! [Файл CSS теперь имеет источник HTML, работающий на локальный сервер] [1]] [1]

Вот мой Node.js

  // Load the http module to create an http server.
    var http = require('http');
    var fs   = require('fs');




 var server = http.createServer(function (request, response) {
   console.log('request was made:' + request.url);

  fs.readFile('index.html', function(err,data){
 response.writeHead(200, {'Content-Type' : 'text/html'});
 response.write(data);
 response.end();
   });


 });



  // Listen on port 8000, IP defaults to 127.0.0.1
     server.listen(8005);

   // send a  message on the terminal
    console.log("Server running at http://127.0.0.1:8005/");

1 Ответ

1 голос
/ 07 апреля 2020

Проблема в обработчике запросов вашего сервера. Вы вручную отправляете index.html для каждого запроса, сделанного браузером. Когда вы переходите к http://127.0.0.1:8005/, ваш сервер пока отправляет index.html пока все хорошо, но затем браузер видит <link href="style.css" rel="stylesheet" type="text/css" title="Default Styles" и запрашивает http://127.0.0.1:8005/style.css, но ваш сервер снова возвращает index.html, поэтому он получает содержимое index.html как это где style.css. Вам необходимо отфильтровать свои запросы к серверу, чтобы ответить правильным файлом. В вашем случае это может быть как:

// Load the http module to create an http server.
var http = require('http');
var fs = require('fs');

var server = http.createServer(function(request, response) {
  console.log('request was made:' + request.url);

  switch (request.url) {
    case '/':
      fs.readFile('index.html', function(err, data) {
        response.writeHead(200, {
          'Content-Type': 'text/html'
        });
        response.write(data);
        response.end();
      });
      break;

    case '/style.css':
      fs.readFile('style.css', function(err, data) {
        response.writeHead(200, {
          'Content-Type': 'text/css'
        });
        response.write(data);
        response.end();
      });
      break;

    default:
      response.end();
      break;
  }
});

// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8005);

// send a  message on the terminal
console.log("Server running at http://127.0.0.1:8005/");

Обратите внимание, что это очень простой c сервер. В нем отсутствует обработка ошибок, его очень трудно масштабировать и поддерживать. Может быть, вы хотели бы попробовать инфраструктуру сервера узлов, например express

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...