簡體   English   中英

使用express.static在js文件之前顯示和加載html

[英]display and load html before js files using express.static

使用express.static時,我很難在瀏覽器中顯示home.html文件的內容。 我的目錄和文件布局為:

dir main
    -server.js
    dir subMain
      dir routing
        -routes.js
      dir public
        -home.html
        -list.html

server.js的代碼

var path = require('path');
var express = require('express');
var app = express();
//Renamed the path with the correct directory names
var htmlRoutes = require('./subMain/routing/routes.js')(app, path, express);

route.js的代碼

module.exports = function(app, path, express){

    //This path.join should lead to 'subMain'
    app.use(express.static(path.join(__dirname + '..')));
    //This path.join should lead to 'app'
    app.use(express.static(path.join(__dirname + '..', '..')));
    app.use(express.static(path.join(__dirname + '..', 'public')));

    app.listen(10003, function(){
        console.log('connected on 10003')
    })
}

目前,我有兩個問題。

1)我嘗試使用express.static而不是sendFile,因為在我的home.html文件中,我有一個指向jquery庫和route.js的鏈接; 當我嘗試執行sendFile時,無法識別jquery選擇器$,因為js在html之前加載。 這就是為什么我試圖使用express.static通過上面的操作加載所有文件的原因。

2)我一直在瀏覽器中收到消息“無法獲取/”。 即使當我取出使用app.use(express.static)的前兩行代碼,而只是在目錄“ public”中具有指向html的那一行時,我仍然會收到此消息。 如何正確顯示home.html並在js文件執行之前完全加載它,以便我可以使用jquery選擇器使按鈕發生點擊事件,從而使Ajax調用GET / list並顯示list.html

您應該在應用程序的頂層(server.js?)聲明靜態文件夾,並全部聲明一次。

暫無
暫無

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

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