简体   繁体   中英

Can't serve static files using express.Router?

Before my file system got a bit more complicated, I used to serve static files through app.use(express.static()) . Now, I'm using express.Router() and I thought I could just change app.use(express.static()) to router.use(express.static()) , but it doesn't work. It throws an error: Refused to apply style from ... because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

Is there a way I can serve static files with router.use() instead of app.use() ?

Filesystem:

/
..../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}`);

Sorry if the question is badly-worded or something in the code looks out of line; this is my first time posting to Stack Overflow and I'm also kinda new to Node, Express, and web servers. I learn to program on my own time.

From the express docs

the path that you provide to the express.static function is relative to the directory from where you launch your node process.

So to take this into account, you should modify 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;

You have to modify your path for the css, as this will be loaded by the server so that use the relative path for server as below.

In your 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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