[英]Can't serve static files using express.Router?
在我的文件系统变得更复杂之前,我曾经通过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 服务器也有点陌生。 我在自己的时间学习编程。
来自快递文档
您提供给 express.static 函数的路径相对于您启动节点进程的目录。
所以要考虑到这一点,你应该修改chat/register/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;
您必须修改 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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.