简体   繁体   English

ExpressJS 不在某些路由上应用 CSS

[英]ExpressJS not applying CSS on certain routes

When I go to localhost:3000 my css works, but when I go to localhost:3000/r/test my css doesn't work and I get this message:当我转到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.

Anytime I have a route where the path is longer than one sub path (I'm not sure if that's even the right term), my css doesn't work at all.每当我有一条路径长于一个子路径的路径时(我不确定这是否是正确的术语),我的 css 根本不起作用。 For example these routes would work:例如,这些路线将起作用:

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

But these won't work:但这些都行不通:

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

My index.js file:我的 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`);
});

My test.ejs file:我的 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>

The structure of my project is:我的项目结构是:

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

Put CSS file in the public directory and add / in href of link like将CSS文件放在公共目录中,并在链接的href中添加/ ,如

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

Now it will request to localhost:3000/style.css every time no matter where you are on the page现在,无论您在页面上的哪个位置,它每次都会向localhost:3000/style.css请求

/ point to the root directory /指向根目录

It would be better to have a separate path to serve the static files最好有一个单独的路径来提供静态文件

Change static path to将静态路径更改为

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

and in the ejs file use it as并在 ejs 文件中将其用作

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM