How to make API request to backend (flask) from frontend(react) running in kubernetes?

3/4/2021

My react code: http-commons.js

export default axios.create({
  baseURL: "http://three-tier-backend-svc.default.svc.cluster.local:5000/",
  headers: {
    "Content-type": "application/json"
  }
});

service.js

create(data) {
    return http.post("/add", data);
  }

When I tried the same command with curl inside the container by using kubectl exec

curl -XPOST -H "Content-type: application/json" -d '{"name": "Mat", "price": 5000, "breed": "Lab"}' http://three-tier-backend-svc.default.svc.cluster.local:5000/add

I get the response:

{"name": "Mat", "price": 5000, "breed": "Lab"}

But the same request doesn't work in frontend in kubernetes Response in chrome

-- tejas waje
api
axios
curl
kubernetes
reactjs

1 Answer

3/4/2021

welcome on Stack Overflow

I think the main issue here is, that your Frontend javascript code (Axios + React) is executed at client-side.

Thus calling external service (three-tier-backend-svc.default.svc.cluster.local) from web browser, using DNS names reserved for Kubernetes in-cluster communication, is failing.

I would suggest you to take a look at three alternative options now:

  1. Expose your backend outside Kubernetes cluster with Service (LoadBalancer/NodePort types).
  2. Expose you backend with Ingress
  3. Consider changing your web app code to be server side rendered.

    1: https://kubernetes.io/docs/concepts/services-networking/connect-applications-service/#exposing-the-service

    2: https://kubernetes.io/docs/concepts/services-networking/ingress/#what-is-ingress

-- Nepomucen
Source: StackOverflow