javascript - js 文件正在加载,但 css 文件未加载
问题描述
在我的index.html
文件中,js 文件正在加载但 css 文件未加载,在access_log
文件中调试后我发现服务器发送带有 200 响应的 css 文件,但我的 html 文件没有加载该文件。
我使用文件将所有请求重定向到index.php
我的服务器上.htaccess
,然后,我尝试直接使用 url 获取 css 文件,它工作正常。
接下来,我在localhost
环境中工作。我有主htdocs
文件夹,它包含所有文件index.php
和index.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]
解决方案
在网络上进行了非常艰苦的搜索后,我发现您必须先设置内容类型,然后才能将任何数据发送到 html,所以在发送 css 或 js 文件之前,我必须在标题上设置内容类型,header('Content-type: text/css');
所以我更改了 index.php 文件中的逻辑以做出不同的响应关于不同的数据类型。
推荐阅读
- c - XErrorEvent 结构体字段含义
- jquery - 无法将动态列数据绑定到 Jquery Gijgo Grid
- vba - 用于保存邮件的本地副本(和重命名本地副本)的宏
- android - 加载图像和 GIF 时如何修复应用程序崩溃?
- javascript - .fill() 等效于对象
- c - 我应该链接哪个库来正确定义 WinRT 的“EXTERN_C const IID IID___x_ABI_*”
- swift - Swift 5 结果类型
- ios - 如何重新制作一周的开始,不是从周日开始,而是从周一开始
- openedx - 如何将 Open edX 从一台机器移动到另一台机器
- c++ - 记录标准输入和标准输出