简体   繁体   中英

How to use express.static in none app.js folder?

I am trying to show the image by using express.static from a server side.

my folder is structure like this..

    public 
     /test.png
    routes
     /index.js
     /upload.js
    app.js

express.static works under app.js ( http://localhost:4000/img/test.png )

    const express = require('express');
    const app = express();
    app.use('/img', express.static(__dirname + '/public'));

    // Server Listen
    const port = process.env.PORT || 4000;

    app.listen(port, () => {
    console.log(`Server running on port: ${port}`);
    });

but it doent work under upload.js ( http://localhost:4000/img/test.png ) what am i doing wrong here? the path seems to be the right one by consoling.

upload.js

    const express = require('express');
    const upload = express.Router();
    const cors = require('cors');
    const path = require("path");

    upload.use(cors());

    console.log(path.join(__dirname + '/../public'));
    upload.use('/img', express.static(path.join(__dirname + '/../public')));

    module.exports = upload;

Here are my index.js and app.js

index.js

    const router = require('express').Router();
    const uploadRoutes = require('./upload');
    router.use('/upload', uploadRoutes);

    module.exports = router;

app.js

     // Import thrid parties for APP
     const express = require('express');
     const cors = require('cors');
     const bodyParser = require('body-parser');
     const app = express();
     const routes = require('./routes');

     // App configuration
     app.use(bodyParser.json());
     app.use(cors());
     app.use(bodyParser.urlencoded({
       extended: false
      }));

     // Route Configuration
     app.use('/api', routes);


     // Server Listen
     const port = process.env.PORT || 4000;

    app.listen(port, () => {
     console.log(`Server running on port: ${port}`);
    });

thank you for looking over this.

我认为它应该像app.use('/img', express.static(__dirname + 'public'));

It isn't necessary to use express.static in both files. It's typically put in the entry file (app.js).

Here's an example from the express docs (notice that the / isn't necessary):

app.use('/static', express.static(path.join(__dirname, 'public')))

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