我怎样才能在端口80上使用node.js服务单页html?

我的项目结构如下所示:

  • 项目
    • 资产/图像/
    • 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一起渲染。

我试过连接,expression和http,但没有运气…新的节点。

谢谢!


首先,改变你的结构:

  • 项目
    • 资产/图像/
    • 资产/ CSS / application.css
    • 资产/ JS / application.js中
    • 资产/字体
    • node_modules
    • 意见/ index.html的
    • server.js
    • 的package.json

首先需要一些包:

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

他们在terminal窗口中运行:

 npm install express 

他们设置configuration:

 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 

他们创build您的路线:

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

如果你想渲染索引,在视图文件夹内:

 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')'); }); 

他们访问本地主机:80 /索引

把你的资产和子目录放在./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...'); });