Not able to connect by frontend to backend on heroku after successful deployment

Viewed 2755

I have deployed my mern stack app on heroku. The problem is i am not able to make any request to my backend . I am connecting my frontend to my backend like this...

API=http://localhost:5000/api

 import { API } from "../../backend";
import { signin } from "../../auth/helper";
export const getAllProducts = () => {
  return fetch(`**${API}/allProducts**`, { method: "GET" })
    .then((response) => {
      return response.json();
    })
    .catch((err) => {
      console.log(err);
    });
};

I think i am caliing api on my local host thatswhy i am not getting connected to backend. What should i do here?

If you want anything else you can tell me .

1 Answers

In client side (frontend) code, localhost is the end user's machine because the code runs in the browser of that machine. Therefore, when it's trying to fetch at localhost:5000/api, it's looking for a Node.js server on the end user's machine, not your actual production server on Heroku.

Instead of localhost, use the domain Heroku assigned to your app. You can find it in the Settings of your dyno and should look something like this https://yourapp.herokuapp.com/. Additionally, you can use NODE_ENV env var to set the API string so it works both on development and production:

const API = process.env.NODE_ENV === 'production' ? 'https://yourapp.herokuapp.com/api' : 'http://localhost:5000/api';
Related