简体   繁体   中英

`express.static` not working inside `express-promise-router`

I'm trying to refactor certain static route in my express app.

First, if i do following inside index.ts , it will works just fine :

import * as express from 'express';
const app = express();
app.use('/something', express.static(path.join(__dirname, '../', 'something')));

However i want to make my code more tidy, so i need to refactor into separate route handler files, ie i create route/something.ts for handling route to /something . So i did following:

Inside index.ts , it become:

import * as express from 'express';
const app = express();
app.use('/something', require('./route/something.ts);

and inside ./route/something.ts :

import * as express from 'express';
import PromiseRouter from 'express-promise-router';
const router = PromiseRouter();
router.route('/')
                .get(express.static(path.join(__dirname, '../../', 'something')));
module.exports = router;

notice that i already change the dir structure from ../ to ../.. but somehow it still doesn't work when trying to hit api endpoint localhost:3000/something/static.jpg it returns error

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Error</title>
    </head>
    <body>
        <pre>Cannot GET /something/static.jpg</pre>
    </body>
</html>

why is this happening? how to solve this? Thanks

This line (in route/something.ts ):

router.route('/')
                .get(express.static(path.join(__dirname, '../../', 'something')));

Should be changed to:

router.use('/', express.static(path.join(__dirname, '../../', 'something')));

You also don't need to use express-promise-router , you can just create the router using const router = express.Router() .

See the routing docs for more info on this.

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