在我的文件系统变得更复杂之前,我曾经通过app.use(express.static())
提供静态文件。现在,我正在使用express.Router()
,我以为可以将app.use(express.static())
更改为router.use(express.static())
,但这是行不通的。它引发错误:Refused to apply style from ... because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
是否可以使用router.use()
而不是app.use()
来提供静态文件?
文件系统:
/
..../chat
......../register
............/styles
................styles.min.css <-- This is the static file I want to serve
............index.html
............index.js
..../routes
........index.js
....index.js
/routes/index.js:
const express = require('express');
const router = express.Router();
router.use('/chat/register', require('../chat/register'));
router.get('/', (req, res) => res.redirect('/chat/register'));
module.exports = router;
/聊天/注册/index.js:
const express = require('express');
const router = express.Router();
router.use('/styles', express.static('styles'));
router.get('/', (req, res) => {
res.sendFile(`${__dirname}/index.html`);
});
module.exports = router;
/index.js:
const express = require('express');
const app = express();
app.use(require('./routes'));
app.listen(process.env.PORT || 80);
console.log(`App is listening on port ${process.env.PORT || 80}`);
很抱歉,如果您的问题措辞不佳或代码中的内容看起来不正确;这是我第一次发布到Stack Overflow,也是Node,Express和Web服务器的新手。我自己学习编程。
答案 0 :(得分:0)
您提供给express.static函数的路径是相对于您启动节点进程的目录的。
因此,考虑到这一点,您应该修改聊天/注册/index.js
const express = require('express');
const path = require('path');
const router = express.Router();
router.use('/styles', express.static(path.join(__dirname, 'styles')));
router.get('/', (req, res) => {
res.sendFile(`${__dirname}/index.html`);
});
module.exports = router;
答案 1 :(得分:0)
您必须修改css的路径,因为它将由服务器加载,以便使用服务器的相对路径,如下所示。
在您的index.js
const express = require('express');
const router = express.Router();
const path = require('path');
router.use('/styles', express.static(path.join(__dirname, 'styles')));
router.get('/', (req, res) => {
res.sendFile(`${__dirname}/index.html`);
});
module.exports = router;