javascript - Express 中的脚本标签

标签 javascript express

我有一个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/

相关文章:

javascript - 仅用于数字和连字符的正则表达式

node.js - 我的请求正文在 Node API 中显示为空或未定义

node.js - nodemon 不工作 : -bash: nodemon: command not found

javascript - 图片上传时禁用发布按钮

javascript - 使用 Codeigniter 安装 CJAX - 错误

javascript - 如何在 mongodb v3.6 中排序

javascript - 确保服务器应用程序在 mocha 测试开始之前运行

javascript - 在 Mongoose 中推送 ObjectId

javascript - .first() 元素不适用于动态生成的 <li>

javascript - Ionic 4 ion-slides第二次忽略slideOptions