【问题标题】:How can I go about serving single page html using node.js on port 80?如何在端口 80 上使用 node.js 提供单页 html?
【发布时间】:2015-04-18 09:16:25
【问题描述】:

我的项目结构如下:

  • 项目
    • 资产/图像/
    • css/application.css
    • js/application.js
    • 字体
    • node_modules
    • index.html
    • server.js
    • package.json

我的目标是能够在项目文件夹中运行“node server.js”并让它在端口 80 上服务。转到 localhost:80 或者我们将渲染 index.html 及其 css/assets/js .

我尝试过使用 connect、express 和 http,但没有运气...node 新手。

谢谢!

【问题讨论】:

    标签: javascript node.js express


    【解决方案1】:

    首先,改变你的结构:

    • 项目
      • 资产/图像/
      • assets/css/application.css
      • assets/js/application.js
      • 资产/字体
      • node_modules
      • views/index.html
      • server.js
      • package.json

    首先需要一些包:

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

    它们在终端窗口中运行:

    npm install express
    

    他们设置了配置:

    app.set('views', path.join(__dirname, 'views')); // This is to serve static files like html in the views folder
    app.set('view engine', html); // your engine, you can use html, jade, ejs, vash, etc
    app.set('port', process.env.PORT || 80); // set up the port to be production or 80.
    app.set('env', process.env.NODE_ENV || 'development'); 
    
    app.use(express.static(path.join(__dirname, 'assets'))); // // This is to serve static files like .css and .js, images, fonts in the assets folder
    

    他们创建你的路线:

    app.get('/', function(req, res) {
      res.send('Hello word');
    });
    
    app.get('/something', function(req, res) {
      res.send('Hei, this is something!!!');
    });
    

    如果你想渲染索引,在views文件夹里面:

    app.get('/index', function(req, res) {
      res.render('index');
    });
    

    最后:

    app.listen(app.get('port'), function(req, res) {
     console.log('Server listening at ' + app.get('port')');
    });
    

    他们访问 localhost:80/index

    【讨论】:

    • 谢谢!它正是我所需要的。但是,在运行“node server.js”时,我收到了这个错误。它是我以前得到的,但从未弄清楚。/Users//Projects/thing/server.js:6 app.set('view engine', html); // 你的引擎,可以使用 html、jade、ejs、vas ^ ReferenceError: html is not defined
    • 首先将 index.html 更改为 index.ejs,然后运行 ​​npm install ejs。它们在文件的顶部,require ejs, var ejs = require('ejs');最后将视图引擎中的“html”更改为“ejs”。
    • 很遗憾没有。收到此错误。错误:在 Function.Module._resolveFilename (module.js:338:15) 处找不到模块“[object Object]”
    • 您可以截屏并上传到 imgur 并在此处发布吗?我在逛街,在iphone里帮你们辛苦了哈哈
    • 您是否安装并需要 EJS??
    【解决方案2】:

    将您的资产和子目录放在 ./public 下,然后从顶部目录添加 app.js:

    var express = require('express');
    var app = new express();
    
    app.use(express.static(__dirname + '/public'));
    
    app.listen(80, function () {
      console.log('Server running...');
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-31
      • 2012-02-06
      • 1970-01-01
      • 2012-02-12
      • 2015-09-28
      • 2013-03-02
      • 1970-01-01
      • 2013-10-02
      相关资源
      最近更新 更多