'Failed to fetch in production react js , rest api

So i hosted my website on heroku . all things went good and was working fine until I went on the page where fetch function was being used. In console (production) it says

Failed to load resource: net::ERR_CONNECTION_REFUSED
QuestionsList.js:9          Uncaught (in promise) TypeError: Failed to fetch
    at QuestionsList.js:9:19
    at s (runtime.js:63:40)
    at Generator._invoke (runtime.js:294:22)
    at Generator.next (runtime.js:119:21)
    at r (asyncToGenerator.js:3:20)
    at i (asyncToGenerator.js:25:9)
    at asyncToGenerator.js:32:7
    at new Promise (<anonymous>)
    at asyncToGenerator.js:21:12
    at QuestionsList.js:8:18

my code in question list component is

const QuestionsList = () => {
  const [data, setdata] = useState([]);
  const fetchData = async () => {
    var x = await fetch("http://localhost:4000/api/v1/post");
    var parsedData = await x.json();
    setdata(parsedData.posts);
  };
  useEffect(() => {
    fetchData();
  }, []);
  return (
    <>
      <div className="container">
        <h2 className="heading-mid currentAffairs mt-3 pt-3">
          Current Affairs!!{" "}
        </h2>
        <div className="row">
          {data.map((element) => {
            return (
              <div className="col md-4" key={element.imageUrl}>
                <Question url={element.imageUrl} />
              </div>
            );
          })}
        </div>
      </div>
    </>
  );
};

I think the problem is in var x = await fetch("http://localhost:4000/api/v1/post"); but cant figure out what to write instead of localhost(I know I have to write my domain name) .like I will change the domain after some time .so instead of hard coding is there any other way?? Thanks in advance.



Solution 1:[1]

I just hardcoded hotname instead of localhost. thanks!

Solution 2:[2]

I think you have to add cors orgin to your rest api server

var express = require('express')
var cors = require('cors')
var app = express()

var corsOptions = {
  origin: 'http://heroku .....com',
  optionsSuccessStatus: 200 
}

//...
app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Arjav Sethi
Solution 2 Hakiki