Node js 作为 http 服务器和主机 angularJS SPA

Node js as http server and host angularJS SPA

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

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

  2. 如果你编写了服务器端代码,(ExpressJS 或 restify web api)然后使用 $>nodemon server.js

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

在您的 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

这个例子对我来说适用于任何情况

即使你有base-url或没有

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}!`))