简体   繁体   中英

Can't set static folder express.js

I'm trying to set a static folder for my index.html file and other folders like css, img and js scripts. but i don't manage to set a static folder successfully. this is my app.js code:

     const path = require('path');
const express = require('express');
const app = express();


app.use(express.static(path.join(__dirname, 'httpdocs')))
// app.get('/', (req, res) => {
//     res.sendFile('index.html')

// });

const PORT = process.env.PORT || 5000

app.listen(PORT, (err) => {
    if (err) {
        console.log(err);
    }
    console.log(`Listening on port ${PORT}`);

})

my file tree is like this:

---node/
     ------httpdocs (i want this to be static folder
           ---css/
           ---js/
           ---img/
           --index.html (this file should be loaded when loading the root link)
   ---app.js (nodejs script)

ps: im using plesk on windows so if this makes any difference tell me.

I can see the only error is in below line.

app.use(express.static(__dirname + 'httpdocs'))

Try to print below tow different method using console :

console.log(__dirname+ 'httpdocs');
console.log(path.join(__dirname, 'httpdocs'));

Output:

...\nodehttpdocs
...\node\httpdocs

I hope you get the solution.

If you are trying to manually merge path then you have to add path separator '\\' externally

Ex: app.use(express.static(__dirname + '\httpdocs'));

Or else use below method

Ex: app.use(express.static(path.join(__dirname, 'httpdocs')));

I suggest using path.join method. Because it will add path separator based on the operating system. Or else you have to manage manually.

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