Different ports for frontend and backend. How to make a request? - express

Using Angular-CLI as a frontend. 4200 port
Using Express as a backend. 8080 port
Directories look like:
Application
- backend
- ...Express architecture
- frontend
-...Angular2 architecture
So I'm running two projects, two commanders, one for frontent, second one for backend. node app.js for backend (8080), ng serve for frontent (4200).
Let's assume that I have a layer in backend which returns some string.
app.get('/hello', function(req, res) {
res.send("Hello!");
}
How can I make a request from frontend to backend and get that string? I don't want to know how exactly should I use Angular2 because that's not the point. I'm asking, what technology should I use to be able connect these two (frontent and backend) sides on different ports. If I just run them and make a request from frontend, I'll get an error because it can't find /hello url.

Your request to /hello means an absolute path inside the application running the angular application, so the request goes to http://localhost:4200/hello. Your angular application just doesn't know about the express application you want to target.
absolute urls
If you want to access the hello route on the other (express) application, you need to explicitly specify this by referencing http://localhost:8080/hello.
cors
Doing it this way, the correct application is targeted, but you will likely run into CORS issues, because the browser will prevent the javascript code obtained from localhost:4200 to access a server at localhost:8080. This is a security feature of your browser. So if you want to allow the code at 4200 to access the backend at 8080 your backend can whitelist this so called origin. For details see http://enable-cors.org/ and a corresponding express middleware you could use to support cors in your backend (https://www.npmjs.com/package/cors).
Using this approach has two downsides in my opinion. First, you need a way to tell your frontend under which absolute url it can reach the backend. This must be configurable because you need different urls for dev, staging and production. You then also need a way to manage all your whitelisted urls because the frontend in production will have a different url than when running the frontend in development. This can get pretty cumbersome to handle.
proxying your backend
A better approach in my opinion is to handle this in your infrastructure by proxying the backend in your frontend application. With proxying you basically tell your frontend server that all requests to some url should be passed through to another application. In your case this could probably mean, that for example you configure a proxy for the path /api/ to proxy the application on localhost:8080. The server then doesn't try to find a url like /api/hello on your frontend application but forwards your request to localhost:8080/hello. In your angular application you then don't need to care about the url of your backend and you can then always do a request to a url like /api/some-express-route.
For this to work you need to configure your angular dev server to proxy the requests. For details on how to do this, please see the docs at https://angular.io/guide/build#proxying-to-a-backend-server. When going to production, you can do this by configuring your web server, e.g. nginx to proxy the requests.

Related

React Front-end connecting to Java Backend on Gitpod HTTPS

I have a project which I have dockerised here: https://github.com/redis-projects/redis-movies/tree/gitpod
I am in the process of trying to get it to work correctly on GitPod, however I am having issues with the frontend react app hitting the backend java service. The react app is running in my local browser so I am confused by which network settings I should use and how to correctly configure.
The docker-compose file when used locally can simply use localhost:8080 to interact with the backend services, but GitPod generates a unique domain over HTTPS. Currently this causes the issues:
Mixed Content: The page at '<URL>' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint '<URL>'. This request has been blocked; the content must be served over HTTPS.
This is self-explanatory, I cant make HTTP requests when the site is loaded via HTTPS. & even if I could, its pointing # localhost so the service wont resolve.
How can I setup my docker-compose + gitpod configuration to correctly configure the React URL
Currently use env vars:
REACT_APP_MOVIE_SERVICE_HOST=localhost
REACT_APP_MOVIE_SERVICE_PORT=8080
and this simply builds a url like so (apiConfig.js): http://${process.env.REACT_APP_MOVIE_SERVICE_HOST}:${process.env.REACT_APP_MOVIE_SERVICE_PORT}
Assuming that the backend services are exposed via a public endpoint, I will need to handle any CORs issues since these services are no longer 'local'?

frontend cloud run app can not access my backend cloud run app due a MixedContent problem

I have two cloud services up and running.
frontend (URL: https://frontend-abc-ez.a.run.app/)
backend (URL: http://backend-abc-ez.a.run.app/)
Frontend is calling the backend through a nuxt.js server middleware proxy to dodge the CORS problematics.
The call is coming through - I can see that in the backend log files. However the response is not really coming back through because of CORS. I see this error in the console:
Mixed Content: The page at 'https://frontend-abc-ez.a.run.app/' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://backend-abc-ez.a.run.app/login'. This request has been blocked; the content must be served over HTTPS.
What I find weird is that I configured the backend url with https but it is enforced as http - at least that is what the error is telling me. Also I see a /login path segment in the unsecure URL. Why is that? I never explicitly defined that endpoint. Is it the security layer proxy of the run service itself?
Anyway - I need to get through this properly and am having a hard time to understand the source of the problem.
For some reason as I rechecked the applications today in the morning everything went fine. I have really no idea why it is working now. I did not change a thing - I waited for the answers here before I'd continue.
Very weird. But the solution so far seems to be waiting. Maybe Cloud Run had some troubles.

Dynamically change API route for SPA

I am currently building a SPA app using Vue.js and webpack to do our bundling. The backend API is built with .Net Core. When running locally, the Vue app is hitting localhost on the backend. I need to be able to change the route of the API dynamically based on the environment. Is there a way to do this without having to do a big switch statement that considers the current url? A requirement is that we are not allowed to change the webpack bundle for different environments, in other words, once it is bundled, it has to stay bundled. I have tried to pass static config files through to the bundle and dynamically change them based on the environment, but unfortunately that does not work, as it hits the values that were originally in them.
webpack dev server has a proxy capability. You could use this to proxy to your locally running backend when developing.
https://webpack.js.org/configuration/dev-server/#devserver-proxy
e.g. you can point anything from '/api' to 'localhost:8888/api' with the config.
Is your app the backend running on the same url when deployed? If not, you'll likely need a reverse proxy to pass along the requests to the backend.
You can use an axios interceptor so you only have that switch in one place:
axios.interceptors.request.use(config => {
// check location.host name and append the backend url you want
});
see https://github.com/axios/axios#interceptors
However, this is a little dangerous as the URLs in your switch statement will be strings, and therefore all of your environment URLs can be pulled out of your code even if minified/concatenated.
Another option is to add some sort of endpoint to the server your client side code is hosted, and when you start your app, query for that configuration.

Separate back-end and front-end apps on same domain?

We are building a fully RESTful back-end with the Play Framework. We are also building a separate web front-end with a different technology stack that will call the RESTful API.
How do we deploy both apps so they have the same domain name, with some URLs used for the backend API and some for the front-end views?
For example, visiting MyDomain.example means the front-end displays the home page, but sending a GET to MyDomain.example/product/24 means the back-end returns a JSON object with the product information. A further possibility is if a web browser views MyDomain.example/product/24, then the front-end displays an HTML page, and that webpage was built from a back-end call to the same URL.
Finally, do we need two dedicated servers for this? Or can the front-end and back-end be deployed on the same server (e.g. OpenShift, Heroku)
You are gonna to dig yourself... deep :)
Simplest and most clean approach with no any doubt is creating a single application serving data for both, BE and FE, where you differ response (JSON vs HTML) by the URL, pseudo routes:
GET /products/:id controllers.Frontend.productHtml(id)
GET /backend/products/:id controllers.Backend.productJson(id)
Benefits:
single deployment (let's say to Heroku)
name space managed from one app
No need to modify the models in many apps after change in one of them
else if
If you're really determined to create a two separate apps, use some HTTP server as a proxy - for an example nginx - so it will send all requests to domain.tld/* to application working at port 9000 (which will answer with HTML) but requests to domain.tld/backend/* redirect to application working at port 9001 responding with JSON.
else
If you are really gonna to response with JSON or HTML depending on the caller you can try to compare headers to check if request was sent from browser or from AJAX call in each controller , but believe me that will become a nightmare faster than you thing... insert the coin, choose the flavor
I thought of a different solution. I'm going to deploy back-end to a subdomain like
http://api.myapp.example/
and deploy front-end to the main domain:
http://myapp.example/
but I think you'd better use 2 different hosts, one for front-end and one for back-end (I searched the Google and this was the result of my investigations
Other possibility (therefore as separate answer) is using a possibility added in Play 2.1.x a Content negotiation I think it's closest for that what you wanted to get initially :)
Indeed its much easier to create a MEAN STACK APP and use one hosting like Heroku for instance.
Your frontend is what it is, front end for your backend. It will be easy to access backend / restfulAPI's and frontend like this:
http://localhost:3000/api/contacts (to access and consume your API endpoint)
http://localhost:3000/contacts (frontend)
NB: localhost:3000 or http://yourapp.example/api/contacts (api)
http://yourapp.example/contacts (frontend)
It's in the URL

Why is same origin policy kicking in when making request from localhost to localhost?

I'm keeping the backend API as a separate project from the frontend HTML5 app consuming it. I'm using Yeoman for the frontend development. Yeoman runs on localhost:3501 and the backend on localhost:3000. When I make the API request from the browser (using AngularJS's $http), I hit the same origin policy:
XMLHttpRequest cannot load http://localhost:3000/venues. Origin http://localhost:3501 is not allowed by Access-Control-Allow-Origin.
AFAIK, same origin policy should kick in only when making request across different domains. Why is it whining when we do a request from localhost to localhost (albeit to different port)?
How can I make this work and will this cause problems in production?
The ports also count for cross domain requests, therefore http://localhost:3000 and http://localhost:3501 are 2 different domains (from browser's point of view).
If you need both applications (client and backend) to run on different ports, consider using http://enable-cors.org/
According to W3C, "An origin is defined by the scheme, host, and port of a URL", so the different port is causing your problems.
Two possible solutions:
CORS (Cross Origin Resource Sharing)
Using JSONP requests
Both would require changes to your backend (I'm not familiar enough wo. CORS would probably mean the least changes to your frontend (I think AngularJS supports it out-of-the-box).