Warm tip: This article is reproduced from serverfault.com, please click

node.js-CSS 和 JS 文件未在节点 js 中链接

(node.js - CSS and JS file not linking in node js)

发布于 2021-01-21 05:34:52

我想使用中间件 func 来提供静态文件,但问题是我的 css 文件没有使用 node 和 express 与 html 文件链接

错误是:

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

应用程序.js:

const express=require('express');

const path=require('path');

const app=express();


app.use('/public',express.static(path.join(__dirname,'static')));


app.get('/',(req,res)=>{

   res.sendFile(path.join(__dirname,'static','index.html'));

});

app.listen(3000);

索引.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>
   <link rel="stylesheet" type="text/css"  href="/static/css/style.css">
</head>
<body>
    <div class="asd">
          Hi xyz here..
          
    </div>
    <script src="/static/js/script.js"></script>
</body>
</html>

文件夹结构为:

 static

   css

     main.css

   js

     script.js

   index.html

 app.js

我尝试了很多,但我无法找到错误,请帮助!!谢谢!!

Questioner
Akshit Trivedi
Viewed
0
Ravi Ojha 2021-01-21 14:13:34

我们将不得不做这样的事情:

应用程序.js

const express=require('express');

const path=require('path');

const app=express();


app.use('/public', express.static(path.join(__dirname,'./static')));


app.get('/',(req,res)=>{

   res.sendFile(path.join(__dirname,'static','index.html'));

});

app.listen(3000, () => {
  console.log("Starting at", 3000);
});

索引.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>
    <script src="/public/js/main.js"></script>
    <link rel="stylesheet" href="/public/css/style.css">
</head>
<body>
    <div class="asd">
          Hi xyz here..
    </div>
    <script src="/public/js/script.js"></script>
</body>
</html>


这是屏幕截图:

最终图像


我们可以想到的一个基本拇指规则:

app.use('<something_here>', express.static(path.join(__dirname,'./static')));
<link rel="stylesheet" href="<something_here>/css/style.css">
<link rel="stylesheet" href="<something_here>/css/style.css">