[英]Flask: Resource interpreted as Stylesheet but transferred with MIME type text/html
[英]Resource interpreted as Stylesheet but transferred with MIME type text/html in cloudflare workers
我正在尝试添加一个外部 css 文件,并且我知道了一种使用此答案添加外部样式表的方法使用 JavaScript添加外部样式表
并使用它我试图添加外部文件,但在这里得到错误是我试图运行的代码
const html = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h2 class="heading">Hello</h2>
<script>
var element = document.createElement("link");
element.setAttribute("rel", "stylesheet");
element.setAttribute("type", "text/css");
element.setAttribute("href", "main.css");
document.getElementsByTagName("head")[0].appendChild(element);
</script>
</body>
</html>`
async function handleRequest(request) {
return new Response(html, {
headers: {
'content-type': 'text/html;charset=UTF-8',
},
})
}
addEventListener('fetch', (event) => {
return event.respondWith(handleRequest(event.request))
})
当我在 Firefox 中运行此代码时,就会出现此错误
样式表https://staticpage.practice.workers.dev/main.css未加载,因为其 MIME 类型“text/html”不是“text/css”。
问题是您从每个路径提供相同的 HTML。
当您在浏览器中访问您的站点时,浏览器首先请求该页面,然后它会按预期返回 HTML。 但是您的 HTML 包含一些 JavaSript,它构造了一个标记,例如: <link rel="stylesheet" type="text/css" href="main.css">
当您的浏览器看到这一点时,它会尝试将main.css
作为样式表加载. 由于这是一个相对路径,它尝试从提供 HTML 的同一服务器加载它。 但是那个服务器是你的工人,你的工人总是返回你的 HTML 来响应每个请求。 因此,当浏览器请求main.css
,它会再次获取 HTML。 这不是有效的样式表,因此它会抱怨您看到的错误。
您可以尝试将您的工作人员的handleRequest()
方法更改为以下内容:
async function handleRequest(request) {
let url = new URL(request.url);
if (url.pathname === "/") {
return new Response(html, {
headers: {
'content-type': 'text/html;charset=UTF-8',
},
})
} else if (url.pathname === "/main.css") {
// TODO: return your stylesheet here.
} else {
return new Response("Not found", {status: 404});
}
}
或者,如果您打算从不同的主机名而不是从您的工作人员加载样式表,那么您应该更改以下行:
element.setAttribute("href", "main.css");
包含完全限定的 URL,例如:
element.setAttribute("href", "https://example.com/main.css");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.