[英]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. 我正在尝试为index.html文件和其他文件夹(如css,img和js脚本)设置一个静态文件夹。 but i don't manage to set a static folder successfully.
但我无法成功设置静态文件夹。 this is my app.js code:
这是我的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}`);
})
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. ps:即时通讯在Windows上使用plesk,所以如果这有什么区别告诉我。
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. 我建议使用path.join方法。 Because it will add path separator based on the operating system.
因为它将基于操作系统添加路径分隔符。 Or else you have to manage manually.
否则,您必须手动进行管理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.