【问题标题】:How do I include an external JavaScript file when serving an HTML file with a response object in expressjs?在 expressjs 中提供带有响应对象的 HTML 文件时,如何包含外部 JavaScript 文件?
【发布时间】:2015-05-19 04:28:50
【问题描述】:

我的 express 应用在初始 GET 时从我的磁盘提供一个 HTML 页面(即,如果我在浏览器中点击“http://localhost:3000/”)。现在我想访问一个 JavaScript 文件,它与 HTML 文件在磁​​盘中的相同位置。当我尝试使用

将其包含在“index.html”中时
 <script src="/myJavaScriptFile.js" type="text/javascript" ></script>

 <script src="./myJavaScriptFile.js" type="text/javascript" ></script>

 <script src="~/MyAbsolutePath/myJavaScriptFile.js" type="text/javascript"</script>

它不起作用。永远无法访问 myJavaScriptFile.js 文件。

我的快递应用如下所示:

 var express = require('express')
 var testMethod = require('./test')
 var app = express()
 app.use(bodyParser.urlencoded({ extended:false }));

 var server = app.listen(3000, function () {

 var host = server.address().address
 var port = server.address().port

 console.log('Example app listening at http://%s:%s', host, port)

 })

 app.get('/', function (req, res) {
 console.log('In /');
 res.sendFile(__dirname + '/index.html');
 })

Express 应用程序使用 res.sendFile 函数使用引用路径“__dirname”+“/index.html”提供“index.html”。 (我开始觉得这是一种不好的做法。如果您也这么认为,请告诉我)。

正如我们在 express 应用程序中看到的,一个名为“test”的外部 JavaScript 文件与“index.html”和“express.js”位于相同的位置,没有任何问题。任何人都可以阐明背景中实际发生的事情吗?如果由 express 应用程序提供,我可以在我的“index.html”中提供的 JavaScript 文件的参考路径到底是什么?谢谢。

【问题讨论】:

    标签: javascript html node.js express


    【解决方案1】:

    服务文件,例如图像、CSS、JavaScript 和其他静态文件是在 Express 中内置的中间件 - express.static 的帮助下完成的。

    将要标记为静态资产位置的目录名称传递给 express.static 中间件以直接开始提供文件。例如,如果您将图像、CSS 和 JavaScript 文件保存在名为 public 的目录中,您可以这样做:

    app.use(express.static('public'));
    

    现在,您将能够加载公共目录下的文件:

    http://localhost:3000/images/kitten.jpg
    http://localhost:3000/css/style.css
    http://localhost:3000/js/app.js
    http://localhost:3000/images/bg.png
    http://localhost:3000/hello.html
    

    More Detail Here

    乐于助人!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-22
      • 2017-09-10
      • 2020-09-25
      • 2017-08-06
      • 2016-02-11
      • 2018-04-01
      相关资源
      最近更新 更多