Serving Angular2 app at a base URL with Express - node.js

I have an Angular2 app up and running and a very simple express server. Is it possible to only serve my application when a user visits '/app' (for example)?
If yes how can it be implemented?
I intend to have multiple Angular apps on different URLs and all of these need scripts. Hence a solution which takes care of which script to handle when would be desired.
Edit- Along with the accepted answer, if using the angular-cli, the 'base-href' has to be set to the URL of the app when building the app.

Yes, that's possible.
You have to define that endpoint as the only one:
app.get('/app', function (req, res) {
res.send(/* your application */)
})

You can use this:
// serve the angular web page
app.get('/', app.use(express.static(path.join(__dirname+'/../../public'))));
Note: change the dir name to reach your directory where contains the angular static files.

Related

Deploy production build of ReactJS with Node express as backend

Hi even after lot of search i am still confused what is correct way to deploy my react app created using create-react-app with express as backend.
I ran npm run build which created build folder. I copied the build folder to be served as static folder of express and had put
app.use(express.static('build'));.
It is working fine for homepage, that is homepage opens when i run my express node server but when i go to anyother link outside homepage it gives 404.
Everything is working fine in developer mode, which i run by npm start command. I just want to know what i am doing wrond here. Let me know anymore info required to understand the problem. Thankyou.
It sounds like you don't have the backend server running. You need to npm start your server, and then npm start your front end if that make sense. They are 2 separate things.
Are you using client-side routing? A popular implementation of that is react-router.
Let say you are trying to access /page1, what client-side routing does is use the JS to toggle between different components to "fake" the routing, instead of rending a new HTML.
Yet, by default when you change routes, the browser does the usual stuff and send a GET request to the server asking for the corresponding HTML file. But since you only have index.html served, that's why you received 404.
You need to add the following at the end of your app.js, right before you call app.listen of your express server to tell the server to always return index.html no matter what route does it received.
/* client-side routing.
* For GET requests from any routes (other than those which is specified above),
* send the file "index.html" to the client-side from the folder "build"
*/
app.get("*", (_, res) => res.sendFile("index.html", { root: "build" }));
// your usual app.listen
app.listen(port, () => console.log("Listening"));

How can I connect my NodeJS/Express backend to my VueJS frontend using only one port on my local machine?

My Vue app is set up using Vue CLI (Webpack) and it's working as it should. My NodeJS/Express REST API is also working properly. However, to run them simultaneously I now start a local server for each of them -- each with its own port. I would like to have both of them communicate over one port.
Localhost:8080 should point to the home page of my Vue App and the API requests should follow localhost:8080/api/...
In my production environment I use one and the same port/URL by serving the Vue App as a set of static files ('dist' folder). In my development environment I don't know how to set this up, however.
I looked around for answers online, but feel lost among all the different terms I have come across (.env, crossenv, nginx, cors) and that I am running in circles.
What would be a good way of setting this up?
Thank you
Edit:
I ended up creating three modes to run my application:
Development
I use one script in a package.json to start the frontend and backend server on different ports, using pm2 to run the servers in the 'background' rather than blocking further commands in the terminal/cmd. I use configured a proxy inside my vue.config.js to redirect my API calls made in the frontend to the right base URL and used cors as middleware to allow requests to my API from other domains/ports.
Staging
I use one script in a package.json to build the Vue app into a folder ('dist' folder inside my backend folder) that is a collection of static files and start the backend server. My backend is set up to know when I want to go into staging mode and then serve the static files in the 'dist' folder.
Production
I use one script in a package.json to build the Vue app into a folder ('dist' folder inside my backend folder) that is a collection of static files and push my backend (incl. the built static files) to Heroku.
Well if you need to run both on the same port you could first build your app so that you receive a dist directory or whatever your output directory is named and set up an express server that serves that app and otherwise handles your api requests
const express = require("express");
const path = __dirname + '/app/views/';
const app = express();
app.use(express.static(path));
app.get('/', function (req,res) {
res.sendFile(path + "index.html");
});
app.get('/api', function (req,res) {
// your api handler
}
app.listen(8080)
Assuming that node and the 'app' will always run on the same server you can just use a template library like ejs.
You would then just bundle the app and api together, assuming that the front-end is tied to the backend, realistically you would not even need to hit the API as you could just return the records as part of the view, however if dynamic elements are needed you could still hit the API.
Now, with that said, if the API is something used by many applications then it would probably make sense to build that out as its own microservice, running on its own server and your frontend would be on its own. This way you have separation of concerns with the API and Vue app.

Establishing a new react app with existing express webpage

I have a website made from nodejs-express and ejs , it has 5 pages home , events , about ,developer ,gallery , so all these pages are delivered using ejs. Now I need to create a web app using react and have it as another page of the website ,I searched throughout the internet i found no articles mentioning this particular scenario.
Please note I dont want my root route to be the react app , when i get a GET request on "/client" I need the react app (client) to load up.
My current senario is expressed in this sand box
https://codesandbox.io/s/integrate-react-app-4dwu0?file=/src/index.js
Where are you hosting this. You can deploy this at reactapp.yourdomain.com and set up a proxy for /client and route it to this one.
Here is your solution.
https://codesandbox.io/s/integrate-react-app-kb1c5?file=/reactAppFiles/index.html
You just need to set static files path and you have to send index.html.
it looks something like this
app.use(express.static(path.join(__dirname, "../reactAppFiles")));
app.get("/client", (req, res) => {
res.sendFile("index.html", {
root: path.join(__dirname, "../reactAppFiles")
});
I hope this answers the question.

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.

Authentication with separated client and server

I have created web application in angular 2 for the client side and NodeJS with express framework for the server-side.
For the client side, I generated the project with angular-cli which runs on a lite-server, so my client and server are running on 2 different services.
I want to integrate ADFS authentication.
To implement the authentication, I am using passport-saml package.
There is a middleware in my server-side API which requires a user to authenticate.
The authentication process works fine when reaching the server directly (without the client).
However, I fail to access the API through the #angular/http.
I tried a simple GET request from the server (with the middleware in the end-point) and as a result I am getting the authentication page without redirection (I don't think it's the core problem, but the actual implementation is).
How should I properly implement the authentication when using separate services to the server and the client?
Hi I was also facing the same issue my angular project was hosted on 4200 port. and my node on 3000 port.
Its difficult to implement passport when we have 2 ports running.
step 1
make angular project static by doing an ng build to public folder .
make sure angular-cli.json has *"outDir": "../public",*
step 2
Now we can use the same node port to access angular roots please add below code in your node app.js
var path = require('path');
// Set Static Folder
app.use(express.static(path.join(__dirname, 'public')));
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'public/index.html'));
});
This will enable your angular project accessible through node port.
step 3:
Now we can add the passport login button in the UI
and give the url twitter
THIS IS not explanatory means feel to ask me the doubts.
You are not giving much detail on what the failed response was when the client did the GET to the server. Was it a 400? 401? 404? 500? did you get a CORS error?
Why are you using GET for your login endpoint. You should be POSTing credentials right in the POST payload?
Anyway, in your angular2 code you should have an auth service with a login method. The login method should do something like ..
login(credentials) {
return http.post(your_server_url, payload);
}
you can then subscribe to the Observable returned by the login method and if all is good router.navigate to the home page or if it did not go well display login error messages.
Set separate urls for ui and server in ..src/environments/environment.ts
export const environment = {
production: false,
BASE_URL: 'http://localhost:4200',
API_BASE_URL: 'http://localhost:5000',
};
In node app.js
app.use('/', express.static('public'));
app.get('*', function (req, res) {
res.sendFile(path.join(process.cwd(), 'public', 'index.html'));
});
In your development environment, you should accomplish this by instructing your Angular CLI to proxy all requests to a backend server running on a separate port whenever you run "ng serve". Angular has good documentation on how to do this at https://angular.io/guide/build#proxying-to-a-backend-server. This will make your development process much faster, because you will not need to manually build your Angular application to test every code change.
When a production build is run, Angular will move the distributed files to the location specified in the "outputPath" property of Angular.json (by default set to "dist/<projectName>"). Your main production server will serve them appropriately from there as mentioned by #Lijo in their answer.

Resources