【问题标题】:ExpressJS not applying CSS on certain routesExpressJS 不在某些路由上应用 CSS
【发布时间】:2021-12-15 10:03:19
【问题描述】:

当我转到 localhost:3000 时,我的 css 可以工作,但是当我转到 localhost:3000/r/test 时,我的 css 不工作,我收到以下消息:

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

只要我有一条路径比一个子路径长的路径(我不确定这是否是正确的术语),我的 css 根本不起作用。例如,这些路线会起作用:

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

但这些都行不通:

app.get('/cats/test', (req, res) => {
    ...
)
app.get('/dogs/blah', (req, res) => {
    ...
)
app.get('/hamster/foo', (req, res) => {
    ...
)

我的 index.js 文件:

const express = require('express');
const path = require('path');
const axios = require('axios');
const app = express();

app.set('view engine', 'ejs');
app.set('views', path.join(__dirname + '/views'));

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

app.get('/', (req, res) => {
  res.render('home');
});

app.get('/r/test', (req, res) => {
  res.render('test');
});

app.listen(3000, () => {
  console.log(`Listening at http://localhost:3000`);
});

我的 test.ejs 文件:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="styles.css">
  <title>Test</title>
</head>
<body>
  <h1>Hi<h1>
</body>
</html>

我的项目结构是:

Project
 |
 +-- public
 |   |
 |   +--styles.css
 |
 +-- views
 |  |  
 |  +-- home.ejs
 |  +-- test.ejs
 |
 +--index.js

【问题讨论】:

    标签: javascript html css node.js express


    【解决方案1】:

    将CSS文件放到public目录下,在href的link like中添加/

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

    现在无论您使用什么 URL,它都会每次都向localhost:3000/style.css 请求。

    /指向根目录

    【讨论】:

      【解决方案2】:

      最好有一个单独的路径来提供静态文件

      将静态路径改为

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

      并在 ejs 文件中用作

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

      【讨论】:

        猜你喜欢
        • 2015-02-09
        • 1970-01-01
        • 2018-10-19
        • 2017-09-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-02
        • 2021-11-29
        相关资源
        最近更新 更多