我有一个index.html,其中有几个脚本标记,但它们都返回 404 错误,而且我不知道如何修复它。目前它们位于顶级目录中并被这样引用。例如<script type="text/javascript" src="./util.js"></script>
。
我尝试使用require('./file.js');
但在我看来,这不是我想要的。这不会让我只能在后端访问吗?它需要与 html 一起提供。
最佳答案
指定给express.static()
的root
路径是 Express 将开始匹配磁盘上文件的目录。
app.use(express.static(path.join(__dirname, 'static')));
<小时/>
该路径也不会成为 URL 的一部分。它与 req.path
结合在一起以类似的方式:
var rootPath = 'orbit'; // from `express.static('orbit')`
console.log(path.join(rootPath, req.path));
// 'orbit/orbit/util.js'
请注意,与评论中的路径相比,orbit
出现了两次,并且缺少 static
:
./static/orbit/util.js
或者,使用上面建议的路径:
var rootPath = path.join(__dirname, 'static');
console.log(path.join(rootPath, req.path));
// "/path/to/your/application/static/orbit/util.js"
// assuming `__dirname` is `/path/to/your/application/`
关于javascript - Express 中的脚本标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34366535/