为了账号安全,请及时绑定邮箱和手机立即绑定

Express Server 的 MIME 类型问题('text/html')

Express Server 的 MIME 类型问题('text/html')

杨魅力 2023-07-06 15:02:29
刚刚在我的学校启动 Express 服务器模块。我做了一个非常简单的网站只是为了尝试一下,但似乎 css 文件没有被执行(在 chrome 的终端 cl 中检查)。拒绝应用“http://localhost:3000/public/style.css”中的样式,因为其 MIME 类型(“text/html”)不是受支持的样式表 MIME 类型,并且启用了严格的 MIME 检查。家:26获取http://localhost:3000/public/einstein-home.jpg 404(未找到)const express = require('express');    const app = express();        app.use(express.static('public'));             app.get('/home', (request, response) => {        console.log('dirname', __dirname);        response.sendFile(__dirname + '/views/home.html')    });        app.get('/about', (request, response) => {        console.log('dirname', __dirname);        response.sendFile(__dirname + '/views/about.html')    });        app.get('/works', (request, response) => {        console.log('dirname', __dirname);        response.sendFile(__dirname + '/views/works.html')    });            app.listen(3000, () => {        console.log('Website about Einstein');    });body {    font-family: Verdana, Geneva, Tahoma, sans-serif;    background-color: #f2f2f2;    margin-top: 0px;    margin-right: 0px;    margin-bottom: 0px;    margin-left: 0px;    font-style: normal;    font-weight: 200;}.container {    width: 90%;    margin-left: auto;    margin-right: auto;    height: 600px;    background-color: #FFFFFF;}header {    width: 100%;    height: 8%;    background-color: #52bad5;    border-bottom: 1px solid #2C9AB7;}nav {    float: right;    width: 50%;    text-align: right;    margin-right: 25px;}header nav ul {    list-style: none;    float: right;}nav ul li {    float: left;    color: #FFFFFF;    font-size: 14px;    text-align: left;    margin-right: 25px;    letter-spacing: 2px;    font-weight: bold;    transition: all 0.3s linear;}ul li a {    color: #FFFFFF;    text-decoration: none;}ul li:hover a {    color: #2C9AB7;}.text {    width: 90%;    text-align: justify;    font-weight: lighter;    line-height: 25px;    float: left;    padding-left: 20px;    padding-right: 20px;    color: #A3A3A3;}
查看完整描述

1 回答

?
ITMISS

TA贡献1871条经验 获得超8个赞

我强烈建议不要滚动你自己的模板:express 是ejs内置的,如果你需要更复杂的东西,添加更好的模板pug或者nunjucks是完美的选择。依靠res.render()生成 HTML 文件,不要使用res.writeres.sendFile

至于为什么事情不能正常工作,请记住阅读如何static工作:你告诉 Express 在进入“真正的”路由之前需要检查哪些目录的 URL 请求,其中 - 关键 - 目录的名称不会映射到 URL。

即如果你有这个:

app.use(express.static('public'))
app.use(express.static('files'))

那么请求yoursite.tld/css/cake.css将首先检查css/cake.cssinside public,然后检查 inside files,然后如果app.get没有路径匹配,它将落入任何可能匹配的路由。


查看完整回答
反对 回复 2023-07-06
  • 1 回答
  • 0 关注
  • 122 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信