Frontend to backend request seems to be wrong

Viewed 81

Hi I am trying to deploy a simple React + Node app to a remote server. Backend started with pm2 and seems ok, frontend works with nginx, but when I try to get data from the db, console sends message

GET http://localhost:8080/v1/names net :: ERR_CONNECTION_REFUSED xhr.js: 177

Not too sure if I need to replace request url with the server IP instead of localhost.

Any help is greatly appreciated.

1 Answers

Yes, you should change all your request from localhost to your deployed address, I would also propose you take a look at .env Files to do it. Node.js Everywhere with Environment Variables!.

usually, you should use .env files to automatically choose the good address when deployed and when coding locally. have a nice day.

example of code with a .env file from the back with mongoose.

mongoose
  .connect(
    `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASSWORD}@cluster0.qvs4c.mongodb.net/${process.env.DB_NAME}?retryWrites=true&w=majority`
  )
  .then(() => {
    app.set("port", process.env.PORT || 5000);

    app.listen(app.get("port"), function () {
      console.log("Node app is running on port", app.get("port"));
    });
  })
  .catch((err) => {
    console.log(err);
  });
example of my .env File.

DB_USER=thatsmydbuser
DB_PASSWORD=thatsmypassword123!
DB_NAME=thatsmydbname

Related