【问题标题】:add css with express and node js用 express 和 node js 添加 css
【发布时间】:2020-01-20 16:38:09
【问题描述】:

请帮助我,因为我整天都在尝试添加 css 文件并且总是失败 app.js 代码:

    var express = require("express");
var app = express();
var path = require('path');

app.set('view engine', 'ejs');

app.set('views', '../node_modules/express/views/');




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



app.get("/",function(req,res){


     console.log("welcome");
    res.render("test");

});



app.listen(3000,function(){
    console.log("connected")   
});

test.ejs 代码:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
    <!--    <link type="text/css" href="app.css">-->
<!--    <link href="/public/app.css" rel="stylesheet" type="text/html">-->
<!--    <link  type="text/css" href="/public/app.css">-->
<!--    <link rel="stylesheet" type="text/css" href="/app.css" >-->

<link rel="Style" type="text/css" href="/app.css" >
</head>
<body>
    <h1>here</h1>

</body>

css代码:

body{
    background-color: green;
}

服务器结构: root-->public-->app.css

我也遇到了错误:由于 MIME 类型(“text/html”)不匹配(X-Content-Type-Options: nosniff)而被阻止。但我解决了它并尝试了很多方法来更改路径并将其与 ejs 保存在同一个文件夹中 提前谢谢你

【问题讨论】:

  • rel="stylesheet" 是正确的。剩下的,听起来你需要为静态文件设置路由。
  • @HereticMonkey 恕我直言,我使用了 app.use(express.static('public'));为静态文件创建路由的方法,我只是尝试连接 1 个 css,所以不需要子文件。我也没有得到你的答案 rel="stylesheet" 是正确的,因为我为 css 链接尝试了很多格式检查 test.ejs 文件,你会从我以前的尝试中找到很多 cmets,我用代码更容易猜出我已经尝试过的内容。无论如何感谢您的帮助
  • 就我而言,注释代码不存在,因为它没有运行。你需要的是&lt;link rel="stylesheet" href="/public/app.css" type="text/css" /&gt;
  • 由于 MIME 类型 (“text/html”) 不匹配 (X-Content-Type-Options: nosniff),导致我的旧问题的解决方案被阻止。感谢您的帮助

标签: css node.js express


【解决方案1】:

在您的 app.js 中

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

【讨论】:

    【解决方案2】:

    在 app.js 中:

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

    在 ejs/html 中:

    &lt;link rel="stylesheet" href="/css/index.css"&gt;

    Serving static files in Express

    【讨论】:

      【解决方案3】:

      好的,谢谢大家,但解决方案只是在公开之前添加 ../

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

      因为 express 在包含 app.js 的服务器文件夹中搜索 public

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-25
        • 2014-04-10
        • 1970-01-01
        • 2019-06-06
        相关资源
        最近更新 更多