I'm building a web app using Angular2, to create the project I'm using Angular2 CLI webpack. Angular2 app uses other external packages also (Eg: Firebase). In addition to that, I need to create a REST API running on node.js
How can I serve both of Angular2 app and REST API using node.js server
- Use
ng build
to build your app into build directory. - Create nodejs app to server the build directory as static content, then create route for api.
Following is an example of nodejs app using express that will serve the Angular2 app:
/*
Put content of angular2 build into 'public' folder.
*/
const html = __dirname + '/public';
const port = 4000;
const apiUrl = '/api';
// Express
const bodyParser = require('body-parser');
const compression = require('compression');
const express = require('express');
var app = express();
app
.use(compression())
.use(bodyParser.json())
// Static content
.use(express.static(html))
// Default route
.use(function(req, res) {
res.sendFile(html + 'index.html');
})
// Start server
.listen(port, function () {
console.log('Port: ' + port);
console.log('Html: ' + html);
});
// continue with api code below ...
Follow the Express node server with Angular 2 CLI document to serve your application through Node.js server. The application is being served Through Node.js and a REST full API. You can design this REST as your requirements.
E.g.
Serve application with http://localhost:5000/app
app.get('/app/*', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'))
});
or
Serve data from REST calls with http://localhost:5000/rest/contacts
app.get('/rest/user', function(req, res) {
res.send({
"id": 2,
"name": "Jhon",
})
});
Based on @NTN-JAVA answer, here's a solution to serve an Angular app from NodeJS server.
Here's the summary from beginning:
npm install -g @angular/cli
ng new PROJECT_NAME
cd PROJECT_NAME
npm install nodemon express cookie-parser body-parser morgan method-override --save
5.Create app.js
:
var express = require('express');
var app = express();
var morgan = require('morgan');
var bodyParser = require('body-parser');
var port = process.env.PORT || 3000;
var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)
var router = express.Router();
console.log('——————————- Run on port '+ port);
/****************************** Router ***************************/
router.get('*', function(req, res){
res.sendFile('index.html', { root: __dirname + '/' });
});
/****************************** /Router ***************************/
//app.use(morgan('dev')); // log every request to the console
app.use(express.static(__dirname + '/')); // Static (public) folder
app.use(bodyParser.urlencoded({extended:true}));// get information from html forms
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(methodOverride());
app.use('/', router); // app.use('/parent', router); call all from localhost:port/parent/*
app.listen(port);
Edit
package.json
file:{ ... "scripts": { "start": "ng build; cp app.js dist/app.js; node dist/app.js", } ... }
npm start
This answer also offers a solution for calling direct URLs from browser and resolving them correctly in your app.
None of the answers worked properly for me. And if it worked, the Angular routing did not work on reload.
So this is how I solved it. Angular routing works even on full page reload.
function getRoot(request, response) {
response.sendFile(path.resolve('./public/angular/index.html'));
}
function getUndefined(request, response) {
response.sendFile(path.resolve('./public/angular/index.html'));
}
// Note the dot at the beginning of the path
app.use(express.static('./public/angular'));
app.get('/', getRoot);
app.get('/*', getUndefined);
NO angular base-href rewrite is required! Just use
ng build
orng build --prod
.
来源:https://stackoverflow.com/questions/39845526/how-to-serve-an-angular2-app-in-a-node-js-server