在同一端口上运行Angular Web App和NodeJS服务器?

我使用Yeoman来build立一个基本的angularjs web应用程序,我使用Grunt来构build和运行,并且我已经制作了一个基本的nodejs服务器,并带有一些angular度应用程序用来获取数据的端点。

然而,我想在同一个端口上运行angular度应用程序和节点服务器,有没有办法从我的节点服务器angular度应用程序服务,而不使用grunt servegrunt serve:dist ? 在从节点服务器提供服务之前,我仍然能够缩小我的angular度应用程序吗?

澄清:例如,如果我去http://localhost/它应该服务angular应用程序,但是,如果我去http://localhost/api/xyz它应该服务的节点端点。

你可以做如下。 文件夹结构

 / /public /dist index.html /models /controllers server.js 

server.js是正常的nodejs服务器启动文件。
public/dist文件夹是构build的输出forms的angular度(由ng build

在server.js文件中,首先定义所有api路由器,然后添加*路由发送index.html文件

 // Set our api routes app.use('/api', api); // <- define api end point // Catch all other routes and return the index file app.get('*', function(req, res) { res.sendFile(path.join(__dirname, 'dist/index.html')); }); 

在这里,我所做的是,如果url是类似于http://localhost/api/xyz那么它会在api路由器中打。 如果url是/ api以外的东西,它会将index.html文件发送到客户端。

注意:在浏览器中你应该导航到像http://localhost/这样的东西,而不是http://locahlost/api 。 通过angular度的应用程序,你应该处理(redirect)未命中路由器的input。

我想你明白了我的观点。 如果你想要更多的例子联系我,我会给你我的代码示例。

然而,我想在同一个端口上运行angular度应用程序和节点服务器,有没有办法从我的节点服务器angular度应用程序服务,而不使用grunt servegrunt serve:dist

你需要确保你正在静态地提供angular度的应用程序 。

如果我去http:// localhost /它应该服务angular应用程序,但是,如果我去http:// localhost / api / xyz它应该服务的节点端点

要在同一个快递服务器上同时支持您的API和您的Angular应用程序,您应该使用路由中间件将您的Angular应用程序与您的API分开。 请看下面的路由是如何在server.js/routes/api.js/routes/api/xyz.js

在从节点服务器提供服务之前,我仍然能够缩小我的angular度应用程序吗?

是的,只需将缩小的Angular代码放在/public/app ,并将其设置为包含在您的html中。

示例布局

下面的代码是如何在同一个快速实例中托pipeAPI的同时为您的Angular应用程序提供服务的示例布局。

项目目录结构

 / /public /app /css /views index.html /routes api.js /api xyz.js server.js 

server.js

 var express = require('express'); var path = require('path'); var server = express(); // Check to see if ENV Variable PORT is set, defaults to 1337 var port = process.env.PORT || 1337; var apiRoutes = require('./routes/api.js'); // Sets up our view engine to load server.set('views', path.join(__dirname, 'views')); server.engine('html', require('ejs').renderFile); server.set('view engine', 'html'); // This will serve anything with in /public as a static file server.use(express.static(path.join(__dirname, 'public'))); // Creates /api section of site // apiRoutes is an Express.Router() instance and contains // all /api sub routes (ie. /api/xyz) server.use('/api', apiRoutes); // Send views/index.html to the client // this contains the landing page for the angular app server.get('/', function(req, res) { res.render('index'); }); // Listen for connections server.listen(port, function() { console.log('Listening on ' + port); }); 

/routes/api.js

 var router = require('express').Router(); var xyzRouter = require('./api/xyz'); router.use('/xyz', xyzRouter); module.exports = router; 

/routes/api/xyz.js

 var router = require('express').Router(); router.get('/', function(req, res) { // handle GET /api/xyz }); module.exports = router;