节点js为http服务器和主机angularJS SPA

时间:2015-07-17 05:14:54

标签: angularjs node.js gruntjs single-page-application httpserver

我有一个写在angularJS上的应用程序,由grunt构建。有没有办法可以从节点js创建一个http服务器并在那里托管它。请分享任何有用的代码段或文档。感谢

3 个答案:

答案 0 :(得分:15)

  1. (最简单)如果您没有任何服务器端逻辑,您只需通过http-server模块从npm服务客户端AngularJS / HTML / css。 https://www.npmjs.com/package/http-server 只需通过安装即可 $> npm install -g http-server 并转到您的客户端文件夹,键入http-server并按Enter键。

  2. 如果你有服务器端代码,(ExpressJS或restify web api),那么使用$> nodemon server.js

  3. 如果您正在查看生产应用程序的选项,请考虑永远/ pm2 https://www.npmjs.com/package/pm2 https://www.npmjs.com/package/forever

答案 1 :(得分:5)

app.js文件中使用以下代码。

var express = require('express');

var path = require('path');
var bodyParser = require('body-parser');
var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname, 'public')));

/* GET home page. */
app.get('/', function(req, res, next) {
  //Path to your main file
  res.status(200).sendFile(path.join(__dirname+'../public/index.html')); 
});

module.exports = app;

使用app.js

运行node app.js文件

答案 2 :(得分:0)

无论如何,此示例对我来说都是有效的

即使您没有基本网址

source code here

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
/**
 * This server should host angular appliation with or without base-url
 * The angular static resources should be under `./public`
 */
var app = express();
app.use(function(req, res, next) {
  console.log('Time:', Date.now() + ":", req.originalUrl)
  next()
})
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: false
}));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/base-here-if-any', express.static(path.join(__dirname, 'public')))

app.get('*', function(req, res, next) {
  //Path to your main file
  res.status(200).sendFile(path.join(__dirname + '/public/index.html'));
});


const port = 3000


app.listen(port, () => console.log(`Example app listening on port ${port}!`))