Angular in a NodeJs Server - node.js

I'm beginner in Angular. I have a nodejs server and I have Angular for the front end. Now I would like to know if it's possible to have just one server for both ?
Because in some videos from youtube, they had one server for node and one server for angular.
Thank you, bye

At a basic level you'd need to set the static path for your built, static Angular files and if you are using Angular routing you'd probably want to direct all requests to your index.html of the Angular project so that Angular can handle all client side routing.
For example, setting the static path for a built Angular CLI project that sits in the default public folder created by express-generator. The example uses dist as that is the default destination of the Angular CLI project when you execute ng build.
app.use(express.static(path.join(__dirname, 'public', 'dist')));
Catch-all route to direct any requests not caught by your Express application route definitions, such as RESTful routes returning JSON data or similar, to the Angular project's index.html:
// some routes
var users = require('./routes/users');
app.use('/users', users);
// other routes
var todos = require('./routes/todos');
app.use('/todos', todos);
// catch-all route
// needs to go AFTER all other express server route definitions
app.use('*', (req, res) => res.sendFile(path.join(__dirname, 'public', 'dist', 'index.html')));
If using Angular CLI, during development you can run the projects separately, using a proxy.
Hopefully that helps!

Yes, it's possible to have one server for both.
You can serve your AngularJS files via your favourite HTTP server (e.g. express) on your NodeJS server as static files like so:
app.use(express.static(path.join(__dirname, 'client')))
Where client is the directory containing your front-end content.

Related

Connect express backend to React frontend (in the same server if possible)

I saw a lot of ways to connect React frontend to express backend (REST API) and i don't understand which one of the them is the most common, organized and friendly. (Axios, componentDidMount function and so on..).
My project divide to backend and frontend libraries which includes a connection to mongoDB in the backend.
I am new to React so i will appreciate any recommendation.
You can easily have both on the same server, all you need to do is. Make an express route that servers your react app's index.html.
app.get('/', (req, res) => {
res.sendFile('./public/index.html');
});
Also, don't forget to serve your static files (css, fonts, etc) using express's own middleware.
app.use(express.static('public'));
After you have done that, you can have your API at /api.

I have express on backend and react on frontend, but i also have admin page working on pug template, how can i run it on one domain

I have express on back-end and react.js on frontend, but i also have admin page with pug view engine, working on express routes, how can i use these in one domain
Expressjs is composable in a really nice way. You can have a top level express application which routes off to sub-express apps and serve your individual services.
Lets say you want to serve your react frontend from www.example.com, your admin (pug views) from www.example.com/admin, and you also want to have an api which serves the react frontend at www.example.com/api`.
You would want something a bit like the following code sample which demonstates the composition of express applications. I've not run the code but it should be enough to get you going.
// This parent app acts as a parent layer and router
// for all your "sub apps". Any middleware you apply
// to this express app will apply to *all your other
// sub-apps*.
const parentApp = express();
// We now create another express instance, this will
// house the API. It can be in another file and you
// could require in something like "require('api');"
// instead but for brevity we'll keep it all in one
// file.
const apiApp = express();
apiApp.get('/info', (req, res, next) => {
console.log('/info');
return res.sendStatus(200);
});
// Mount the sub app on the /api route. This means
// you can how hit 'www.example.com/api/info' and
// you'll get back a 200 status code.
parentApp.use('/api', apiApp);
// Now we setup the admin app which we'll add pug
// views into. This is an example so just pretend
// the views exist.
const adminApp = express();
adminApp.set('views', './views');
adminApp.set('view engine', 'pug');
adminApp.get('/login', (req, res, next) => {
return res.render('login', { title: 'Hey' });
});
// Mount the sub app on the /admin route. This way
// we can hit www.example.com/admin/login to get
// our login page rendered.
parentApp.use('/admin', adminApp);
// Now we create and mount the frontend app that
// serves our fully built react app. You could do
// this with nginx instead but you wanted to do
// it with express so lets do it that way.
const frontendApp = express();
frontendApp.use(express.static('/frontend));
parentApp.use('/', frontendApp);
If you'd rather not create yourself a top level express app (and thus creating a bit of a monolith application) then I'd recommend checking out the nginx documentation, or the docs for the HTTP server you use. You should be able to direct requests to particular endpoints to different node applications running on different ports. Static files can then be served natively by your HTTP server. This is definetely a more efficient and elegant approach, but since you asked about express I wanted to showcase that approach primarily.

How to create a node based server to serve REST API and also deploy the application.

I am new to nodeJS server area, need help in understanding how to work with REST API (using express) and deploy the angular application over a singe node server and same ports.
By deploying i want to understand if user hit below url http://localhost:8000/<page_name> then the specified page should open.
And is user hit below url using get or post request
http://localhost:8000/api/<api_name> then a json or a text will be returned.
How to run both the thing over a single node server.
Lets assume, you have all your static files in the /public folder of you app. Generally spoken, if you are using express.static, you should also get your index.html because this is handled by default for each directory.
In your case, as you are using Angular, the routing is handled from the client side (SPA). You should only have one single index.html after building your Angular app. All files from your dist folder should then be placed into your /public folder. Then you need to make sure, that initial file serving provides your index.html like so:
In this example static files are served first, then your API and if nothing is found, you are getting back you index file.
const express = require('express');
const app = express();
// serve static files
app.static(__dirname + '/public'));
// serve your API
app.get('/api/welcome', function (req, res) {
res.send('Welcome');
});
// fallback routing (server side handling)
app.get(/.*/, function (req, res) {
res.sendFile(__dirname + ‘/public/index.html‘
});
app.listen(3000);
Next time please make sure, to give all necessary information in your question ;-)
With the help from Sebastian, so far I can find a solution but its not working when i am hitting URL for different pages.
const express = require('express');
const app = express();
app.use(express.static('public'))
Please provide your suggestions.

Bundle Angular Universal app with custom nodejs/express server

I just want to know the correct way to serve an angular universal app with an existing nodejs/express server that talks to a Mongodb database and serves data with an "/api/*" route for example.
So is it to have the universal app have its own node/express server as explained here https://angular.io/guide/universal and just merge that with the existing node/express server with route configuration as done here Serve angular universal app with NodeJS/ExpressJS back-end and allow both the custom node/express server and the universal apps express server have different ports (because i assume that is how they will be able to co-exist in production)
Or do we use the custom node/express server as the server for the universal app with proper configuration.
To serve angular app with node server first you need to build the app just run the below command
ng build
And then add two lines of code in your node server file as
app.use(express.static(__dirname + '/dist'))
app.use(function(req, res) {
res.sendFile(__dirname + '/dist/index.html')
})
And after that you can run node server and the default entry index html file will open when you hit the host.

Angularjs4 with express generator

Just developed a simple angular 4 application with this tutorial
https://scotch.io/tutorials/mean-app-with-angular-2-and-the-angular-cli
But how can i integrate angular 4 app to a express application that generated with express generator??.
One approach is REST API's method that is express JS app use as API provider and the angular application communicate with REST api.
But i would like to serve the angular application from express application itself..
I think this will helpful to you. First I assume, you use express server to handle some api request and let's say those routes are begin with /api. they can be differ from yours.
First build your angular application by ng build and it will create a folder called /dist in your project folder.
Copy that folder in to your express project /public folder. You have to put them in an static routed folder. /public folder is a default static route folder. That is why I put it there. If you have your own one, you can put there too.
edit your app.js file as follows
// Set our api routes
app.use('/api', api); // API router definitions.
// Catch all other routes and return the index file
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
Hope you will help this way. Thanks.
You can serve it through your server like this:
// Catch root route and return index.html
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'app/index.html'));
});
// Catch all other routes
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'app', req.originalUrl));
});
But be careful to set the right path to your index.html.
There is a technology stack called MEAN which means (coincidence :) MongoDB, Express, Angular and Nodejs. So this is basically what you are looking for.
Altough you can create you own file structure, there is a mean-cli similar to Express-generator and the angular-cli. You can find it here.
In order for Angular to work properly (like requesting a site like example.com/something and then also activate the route something) I always return my index.html for any request and setup express to return all static files as well. Then I create a route /api which handles all my REST api requests.
Make sure to first setup your /api route, then your other static files from angular like bundle.js and finally index.html as route **.

Resources