Home > other >  Route by path in front web applications using nginx or kukbernetes ingress
Route by path in front web applications using nginx or kukbernetes ingress

Time:04-08

Suppose I own a domain name xxx.yyy.com, but I doesn't own any subdomain name (*.xxx.yyy.com) of it.

So I have to route each HTTP request to its corresponding service by path. For example, routing xxx.yyy.com/app1/ to service app1 and xxx.yyy.com/app2/ to service app2.

I config my kubernestes resources as below:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
    kubernetes.io/ingress.class: "nginx"
spec:
  rules:
    - host: xxx.yyy.com
      http:
        paths:
          - pathType: Prefix
            path: "/app1"
            backend:
              service:
                name: app1
                port:
                  number: 8000
          - pathType: Prefix
            path: "/app2"
            backend:
              service:
                name: app2
                port:
                  number: 8000
---

apiVersion: v1
kind: Service
metadata:
  name: app1
spec:
  selector:
    app: app1
  ports:
    - protocol: TCP
      port: 8000

---

apiVersion: v1
kind: Service
metadata:
  name: app2
spec:
  selector:
    app: app2
  ports:
    - protocol: TCP
      port: 8000

This works in most of the cases, except in front webapps.

In a front webapp's HTML and javascript code, we refer its assets (images, HTTP APIs) on the backend server by root path ("/") , as if it is deployed on its own server.

For example in the javascript code of app1 , we call fetch('/api/getUsers') instead of fetch('/app1/api/getUsers'), so the ingress failed to route /api/getUsers to service app1.

I know it can be solved easily by routing request by host not by path. But I don't have the permission to create subdomains.

So how can this scenario of front webapps be solved by routing by path ingress?

CodePudding user response:

In your application use window.location.href and parse the first part of the URL and use it as base for your requestes.

const url = new URL(window.location.href);
const appName = url.pathname.split('/').length > 2 ?  url.pathname.split('/')[1] : "";
const baseApiUrl = new URL(appName, url).toString();

fetch(baseApiUrl   '/api/getUsers')
     .then((res) = {})
     .catch((error) => { console.log(error)})

CodePudding user response:

When the Web application is available to the Browser beneath a certain path, the front end requests need to target that path. You can achieve this by

  • using only relative path names like api/guestUsers instead of /api/guestUsers
  • or prefixing every query url with that path, like /app1/img/logo.png.

The second way is supported by, for example by:

This setting could be dynamicly filled with a server variable or even set automatically to the location of the entry point.

  • Related