首页 > 解决方案 > 资源解释为样式表,但使用 MIME 类型 text/html 传输:“http://localhost:4000/style.css”

问题描述

我正在使用 deno、橡木和denjucks。文件结构如下 -

index.html
index.ts
style.css

我使用的代码如下 - index.ts 是 -

import {Application, send} from "https://deno.land/x/oak/mod.ts";
import denjucks from "https://deno.land/x/denjucks/mod.js";
const app = new Application();
const HOST = "http://localhost";
denjucks.configure('', { autoescape: true });
const PORT = 4000;
let res = denjucks.render("index.html", {txt: "World"});
app.use(async (context) => {
  context.response.body = res;
  });

console.log(`Server started at: ${HOST}:${PORT}`);
await app.listen({ port: PORT });

index.html -

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./style.css" type="text/css">
    <title>Document</title>
</head>
<body>
    <h1>{{txt}}</h1>
    <h1>Hello World</h1>
</body>
</html>

样式.css -

body{
    background: tomato;   
}

当我执行代码 deno run --allow-all index.ts 时,在 chrome 开发人员工具控制台中出现警告消息 -资源解释为样式表,但使用 MIME 类型 text/html 传输:“ http://localhost:4000/style. .css。并且css代码不适用。此故障背后的原因尚不清楚。

标签: templatesdenooak

解决方案


你所有的路线都在服务text/html,因为你总是回应denjucks.render("index.html", {txt: "World"});,所以当你请求时,style.css你会回应index.html

您需要设置一个静态文件中间件,以便./style.css正确提供服务。

app.use(async (context) => {
  await send(context, context.request.url.pathname, {
    root: `${Deno.cwd()}`
  });
});

app.use(async (context) => {
   context.response.body = res;
});

推荐阅读