簡體   English   中英

在expressjs中使用響應對象提供HTML文件時,如何包含外部JavaScript文件?

[英]How do I include an external JavaScript file when serving an HTML file with a response object in expressjs?

我的快遞應用程序在初始GET時從我的磁盤提供HTML頁面(即,如果我在瀏覽器中點擊“ http:// localhost:3000 / ”)。 現在我想訪問一個與HTML文件位於磁盤相同位置的JavaScript文件。 當我嘗試使用時將其包含在'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'提供服務。 (我開始覺得這是一種糟糕的做法。如果你這么想,請告訴我)。

另外,正如我們在快遞應用程序中看到的那樣,包含“test”的外部JavaScript文件與“index.html”和“express.js”位於同一位置,沒有任何問題。 有誰能請說明背景中實際發生的事情? 如果由快遞應用程序提供,我可以在我的'index.html'中提供的JavaScript文件的參考路徑究竟是什么? 謝謝。

借助Express - express.static中的內置中間件,可以完成服務文件,如圖像,CSS,JavaScript和其他靜態文件。

將目錄的名稱(將標記為靜態資產的位置)傳遞給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

更多細節在這里

快樂幫助!

暫無
暫無

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

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