在我的文件系统变得更复杂之前,我曾经通过 app.use(express.static())
提供静态文件。现在,我正在使用 express.Router()
并且我想我可以将 app.use(express.static())
更改为 router.use( express.static())
,但它不起作用。它抛出一个错误:拒绝应用来自...的样式,因为它的 MIME 类型('text/html')不是受支持的样式表 MIME 类型,并且启用了严格的 MIME 检查。
有没有办法可以使用 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;
/chat/register/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 服务器也有点陌生。我利用自己的时间学习编程。
最佳答案
the path that you provide to the express.static function is relative to the directory from where you launch your node process.
因此,考虑到这一点,您应该修改 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;
关于javascript - 无法使用express.Router 提供静态文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59960222/