首页 > 解决方案 > js 文件正在加载,但 css 文件未加载

问题描述

在我的index.html文件中,js 文件正在加载但 css 文件未加载,在access_log文件中调试后我发现服务器发送带有 200 响应的 css 文件,但我的 html 文件没有加载该文件。

我使用文件将所有请求重定向到index.php我的服务器上.htaccess,然后,我尝试直接使用 url 获取 css 文件,它工作正常。

接下来,我在localhost环境中工作。我有主htdocs文件夹,它包含所有文件index.phpindex.html;另外,它包含资产文件夹,其中放置了我的 js 和 css 文件。

.html 文件:

<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link media="all" rel="stylesheet" href="/assets/test.css" type="text/css" />
  <title>Chat</title>
</head>
<body>
  <div class="top_bar">
    <h1 id="status"></h1>
  </div>
  <div id="test" class="wrapper">
  </div>
  <div class="bottom_bar">
    <form class="text" onsubmit="onEnter(); return false" autocomplete="off">
      <input type="text" name="text" placeholder="Type here" id="text" />
    </form>
    <button id="send">
    </button>
  </div>
  <script src="assets/chat.js"></script>
</body>

我的 index.php 文件:

<?php

$raw_url = $_SERVER['REQUEST_URI'];

$url = explode('?', $raw_url);

$route = $url[0];

$query = $url[1];

if (substr($route, 0, 8) == '/assets/') {
  $file_name = substr($route, 8);
  if(file_exists('assets/' . $file_name)) {
    readfile('assets/' . $file_name);
  }
  else {
    http_response_code(404);
  }
} else {
  switch ($route) {
    case '/':
      readfile('index.html');
      break;
    default:
      http_response_code(404);
      break;
  }
}
?>

.htaccess 文件:

RewriteEngine on
RewriteRule (.*) index.php
RewriteRule ^assets/ - [L,NC]

标签: javascriptphphtmlcssapache

解决方案


在网络上进行了非常艰苦的搜索后,我发现您必须先设置内容类型,然后才能将任何数据发送到 html,所以在发送 css 或 js 文件之前,我必须在标题上设置内容类型,header('Content-type: text/css');所以我更改了 index.php 文件中的逻辑以做出不同的响应关于不同的数据类型。


推荐阅读