簡體   English   中英

無法設置靜態文件夾express.js

[英]Can't set static folder express.js

我正在嘗試為index.html文件和其他文件夾(如css,img和js腳本)設置一個靜態文件夾。 但我無法成功設置靜態文件夾。 這是我的app.js代碼:

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

})

我的文件樹是這樣的:

---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:即時通訊在Windows上使用plesk,所以如果這有什么區別告訴我。

我可以看到唯一的錯誤是在下面的行中。

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

嘗試使用控制台在下面打印兩種不同的方法:

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

輸出:

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

希望您能找到解決方案。

如果您嘗試手動合並路徑,則必須在外部添加路徑分隔符“ \\”

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

否則使用下面的方法

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

我建議使用path.join方法。 因為它將基於操作系統添加路徑分隔符。 否則,您必須手動進行管理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM