Home > Mobile >  How to connect a frontend application on a different port with a backend?
How to connect a frontend application on a different port with a backend?

Time:06-15

I put my frontend application in the public folder for a node.js application and am getting the form-data using the following request:

try {
  await axios.post("/api/v1/contact-form", {
    name,
    email,
    msg,
  }); 
}

My backend is in port 5000 and it's handling the request by:

app.use("/api/v1/contact-form", submitFormRouter);

It works perfect. I'm getting the data when I have my frontend application is in the node.js public folder.

My question is if my frontend is running on a different local port such as, if I use "Five server" to run the frontend application, how do I replace the following path for post:

Frontend:

try {
  await axios.post("/api/v1/contact-form", {
    name,
    email,
    msg,
  });
}

Backend:

app.use("/api/v1/contact-form", submitFormRouter)

I've also tried the code using React in which case the frontend is running in http://localhost:3000/ and node.js server running in 5000, the code still works and I'm getting the form data. But, how do I make it work for a frontend application sitting in a different port(without react)?

Additionally, I hope you're kind enough to answer the following question- What would be the path once I have the frontend let's say on Netlify whereas the backend is on Heroku?

CodePudding user response:

What would be the path once I have the frontend let's say on Netlify whereas the backend is on Heroku?

Let's assume your Back on Heroku has this url https://app.herokuapp.com/ and the Front on Netlify this one https://app.netlify.com/. All you have to do is to give your Front your Back's url, like so:

try {
  await axios.post("https://app.herokuapp.com/api/v1/contact-form", {
    name,
    email,
    msg,
  });
}

My question is if my frontend is running on a different local port such as, if I use "Five server" to run the frontend application, how do I...

At this point you have two choices, the simplest one is to use a complete url like above. Let's assume your Front is on port 3000 and the Back on 8080. All you have to do again is:

try {
  await axios.post("http://localhost:8080/api/v1/contact-form", {
    name,
    email,
    msg,
  });
}

The second one is to use a proxy, and this really depends on your projects' structure and need.

  • Related