javascript - 无法使用express.Router 提供静态文件?

标签 javascript node.js express

在我的文件系统变得更复杂之前,我曾经通过 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 服务器也有点陌生。我利用自己的时间学习编程。

最佳答案

来自express docs

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/

相关文章:

javascript - Webpack 外部依赖

node.js - 每个 axios 请求在 React-Redux 应用程序中都会触发两次?

javascript - TypeError : req. checkBody(...).optional(...).isDate 不是函数

javascript - 如何在React Hooks中的对象内部的方法中访问对象属性

javascript - 如何在angularjs中执行路由

javascript - 无法读取未定义的属性 'concat'

javascript - webpack-dev-server 不会自动重新加载和构建 - 配置问题

node.js - 为什么我可以使用绝对路径而不是相对路径将 Formidable 文件上传到文件夹?

javascript - React Router 仅当从 root url 启动时才能够进行路由

javascript - 在javascript代码中插入href和img