繁体   English   中英

需要在JS文件之前加载并显示HTML文件,express.static不提供HTML文件

[英]Need to load and display HTML file before JS file, express.static not serving HTML file

在我的server.js文件中,我有以下内容

var path = require('path');
var express = require('express');
var app = express();
var htmlRoutes = require('./app/routing/routes.js')(app, path, express);

在我的route.js中

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

    app.use(express.static(__dirname + '/../public'));

    //also tried doing 
    //app.use('/', express.static(__dirname + '/../public'));

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

我不确定为什么我会在浏览器中不断收到消息“无法获取/”。 我的目录布局如下

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

我想做的是,当我运行“ node server.js”时,我想加载并显示route.js文件之前的home.html页面。 这是因为我需要加载文档,以便可以使用jquery选择器“ $”并在home.html中选择一个按钮类,并为其提供一个单击事件,该事件将对“ / list”进行AJAX调用以显示list.html 。

我也尝试过

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

    app.use(express.static(__dirname + '/../..'));

    app.use(function(request, response, next){
        response.sendFile(path.resolve(__dirname + '/../public/home.html'));
    })

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

但我收到以下错误

未捕获到的SyntaxError:意外令牌<

我也尝试过使用多行express.static

module.exports = function(app, path, express){
    //loading the directory with the home.html
    app.use(express.static(path.join(__dirname + '..', 'public')));
    //loading directory with server.js by going up two level, from routing directory -> app -> main (has server.js)
    app.use(express.static(path.join(__dirname + '..', '..')))

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


//Edit, added jquery event handler for button click on home.html
$(document).on('click', '.btn', sendSurvery);

    function sendSurvery(){

        var myQueryUrl = "http://localhost:10003/survey";

        $.ajax({url: myQueryUrl, method: 'GET'}).done(function(response){

        });
    }

但是我仍然收到消息无法获取/。 我需要首先显示home.html以便加载其中的jquery库,因此我可以选择按钮并在click事件上发送survey.html,而我忘记了我的公共目录和路由都在名为subMain的子文件夹中

尝试这个

您的服务器文件应如下所示

    var path = require('path');
var express = require('express');
var app = express();

require('./subMain/routing')(app, path, express);
    app.listen(9000, function(){
      console.log('connected on 9000')
    })

此外,将您的route.js的名称更改为index.js。 将其保存在路由文件夹中(不要更改名称)。 下面的代码应该在其中。 我还更改了您的端口号。 不应该那么高。

      module.exports = function(app, path, express){
    app.use(express.static(__dirname + "/public"));
    app.use(function(request, response, next){
      response.sendFile(process.cwd() + "/subMain/public/home.html");
    })
}

我已经将所有内容发布在github仓库中,因此您可以看到文件结构。

https://github.com/eliezerwohl/stackoverflowAnon

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM