【问题标题】:Express.js not sending css fileExpress.js 不发送 css 文件
【发布时间】:2020-04-20 12:06:21
【问题描述】:

我正在使用 exprss.js 和 socket.io 设置 Web 服务器。我设置了一个静态文件夹,这样我就可以链接我的样式表,而不必发送每个文件。但是我收到了这个错误

Refused to apply style from 'http://localhost:3000/public/styles/index.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

这是我的 app.js 文件

const express = require("express");
const app = express();
var server = require('http').Server(app);
var io=require('socket.io')(server);

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

app.get('/', function (req, res) {
    res.sendFile(__dirname + '/public/views/index.html');
});

io.on('connection', function(socket){
    socket.emit('chat message', {hello: 'world'});
    socket.on('chat message', function (data){
        console.log(data);
    });
});

server.listen(3000);

index.html 页面如下所示

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <link type="text/css" rel="stylesheet" href="/public/styles/index.css">
</head>
<body>
<p>yo</p>
</body>
</html>

文件结构如下

|-public
   |-styles
     -index.css
   |-views
     -index.html
-app.js

我认为我的服务器设置有问题 这是我第一次使用节点

【问题讨论】:

  • 这能回答你的问题吗? Express serve static files in nested directory
  • href 属性中删除/public,使其成为&lt;link type="text/css" rel="stylesheet" href="/styles/index.css"&gt; express.static('public') 在根/ 处提供公用文件夹

标签: html css node.js express server


【解决方案1】:

当该链接下没有 CSS 文件时,通常会出现此错误。

当您直接使用app.use(express.static('public')); 时,express 服务于根端点下的所有内容。

所以你可以使用&lt;link type="text/css" rel="stylesheet" href="/styles/index.css"&gt;

如果你想使用/public/xxx.css,你可以使用

app.use('public', express.static('public'));

【讨论】:

    【解决方案2】:

    当你使用静态时,原始文件夹不包含在路径 url 中,试试这样:

    <link type="text/css" rel="stylesheet" href="/styles/index.css">
    

    【讨论】:

      猜你喜欢
      • 2021-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      • 2016-08-29
      • 2014-04-06
      • 2020-05-21
      • 1970-01-01
      相关资源
      最近更新 更多