Search code examples
reactjsexpressherokuget

Failed to Load resource: net:: ERR_CONNECTION_REFUSED? Heroku, Axios


After deploying my app to Heroku I noticed that the route to get the house data is not working and returns these error in the console Failed to Load resource: net:: ERR_CONNECTION_REFUSED and Uncaught (in promise) Error: Network error. the route works on my local machine but, not on the deployed application. I suspect it could be an issue that deals with cors, but I'm not sure why this one single route will not work.

Component


import React, { useEffect, useState } from "react";
// import { useHistory } from 'react-router-dom'
import axios from "axios";
// import BackspaceIcon from '@material-ui/icons/Backspace';
// import FullscreenExitIcon from '@material-ui/icons/FullscreenExit';
import ArrowBackIosIcon from "@material-ui/icons/ArrowBackIos";
import "../StyleSheet/SingleHouse.css";
import placeholder from "../images/placeholder-image.jpg";


import { Link ,withRouter} from "react-router-dom";

const SingleHouse = (props) => {
  // const house_id = window.location.href.split("/")[4];

  // console.log('HOUSE ID: ', house_id);
  //GET HOUSE OBJECT, USESTATE

  const url = `http://localhost:5000/api/house-details/${props.match.params.id}`;
  const [showLoading, setShowLoading] = useState(true)
  
  const [house, setHouses] = useState("");

  

  useEffect(() => {
    const fetchData = async () => {
      const result = await axios(url);
      setHouses(result.data);
      setShowLoading(false);
    };
  
    fetchData();
  }, []);

  async function handleDelete() {
    try {
      await axios.delete(`${url}`);
      props.history.push("/house-sale");
    } catch (error) {
      console.error(error);
    }
  }

  // console.log(house)

  return (
    <div className="HosueDescription__container">
      {house && (
        <div className="HouseDescription__leftContainer">
          {house.isSaleOrRent === "SALE" ? (
            <Link to="/house-sale">
              <ArrowBackIosIcon className="icon" />
            </Link>
          ) : (
            <Link to="/house-rent">
              <ArrowBackIosIcon className="icon" />
            </Link>
          )}
          <div className="houseImg-container">
            <div className="img__container">
              <img
                className="img-fluid"
                src={house.house_image}
                alt="house-image"
              />
            </div>
            <div className="placeholder-container">
              <img
                className="placeholder"
                src={placeholder}
                alt="placeholder-img"
              />
              <img
                className="placeholder"
                src={placeholder}
                alt="placeholder-img"
              />
            </div>
          </div>
          <div className="number_container">
            <h3 className="housePrice">{`$${house.price.toLocaleString(
              navigator.language,
              { minimumFractionDigits: 0 }
            )}`}</h3>
            <h5> {house.numOfBeds} bd |</h5>
            <h5> {house.numOfBaths} ba |</h5>
            <h5>
              {" "}
              {house.squarefeet.toLocaleString(navigator.language, {
                minimumFractionDigits: 0,
              })}{" "}
              sqft
            </h5>
          </div>

          <div className="houseText">
            <h3 className="houseDetails">{`${
              house.numOfBeds
            } Bedroom house in ${
              house.city.charAt(0).toUpperCase() + house.city.slice(1)
            } for ${house.isSaleOrRent}.`}</h3>

            <h4>
              2423 Duck Creek Road,{" "}
              {house.city.charAt(0).toUpperCase() + house.city.slice(1)},{" "}
              {house.us_state.charAt(0).toUpperCase() + house.us_state.slice(1)}
            </h4>

            <h4>
              Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quasi
              fugiat autem cumque voluptas? Ratione error reprehenderit delectus
              odio quos iure soluta adipisci fugit, dolores amet neque! Quaerat
              ipsum laborum consectetur rem voluptas, ullam quisquam aut
              eligendi nesciunt culpa ad totam, corporis a! Velit consequatur
              molestias dolor corrupti iure sequi id expedita repellendus
              impedit neque. Impedit cupiditate laboriosam commodi aperiam nobis
              odio sunt, error adipisci atque ex minima nisi dignissimos unde!
              Quod est laudantium, neque dolor atque itaque. Est, dignissimos
              eum.
            </h4>
          </div>
          <Link to={`/edit/${props.match.params.id}`}> <button>Edit House</button></Link> 
          <Link to="/house-sale">
            {" "}
            <button onClick={handleDelete}>Delete House</button>
          </Link>
        </div>
      )}
      <div className="edit-from"></div>
    </div>
  );
};

export default withRouter(SingleHouse)

back-end route

router.get('/api/house-details/:id', async(req, res)=>{

    await House.findById(req.params.id).exec().then(data=>{

        return res.status(200).json(data)
    }).catch(error =>{
        return res.status(400).json(error)
    })
})

server.js


// require("dotenv").config({path: "./.env"});
const express = require("express");
const cors = require('cors')
const app = express()
const path = require('path')
require("dotenv").config()
const bodyParser = require('body-parser')
// const bodyParser = require("body-parser")


//MIDDLEWARE
app.use(cors())

app.use(function(req, res, next) {
    res.header('Access-Control-Allow-Origin', 'http://localhost:5000');
    res.header(
      'Access-Control-Allow-Headers',
      'Origin, X-Requested-With, Content-Type, Accept'
    );
    next();
  });

app.use(bodyParser.json())
// app.use(bodyParser.urlencoded({ extended: true }));

//App Routes files

const houseRouter = require('./Routes/HouseListing/HLRoute')
const houseFetchRoute = require('./Routes/HouseFetchRoutes/HouseFetch')


//App route
app.use(houseRouter)
app.use(houseFetchRoute)

if(process.env.NODE_ENV === "production") {
    app.use(express.static(path.join(__dirname, '/client/build')));

    app.get("*", (req, res)=>{
        res.sendFile(path.join(__dirname, 'client', 'build', 'index.html'));
    })
} else {
    app.get('/', (req, res)=>{
        res.send('API RUNNING')
    })
}


//server entry point
const PORT = process.env.PORT || 5000;

app.listen(PORT, () =>{
    console.log(`Server is runnning on port: ${PORT}`)
})



Solution

  • The issue is you're hardcoding the API URL. You have to use the URL depending on the environment the code is being run on (localhost on development and the production API URL on production).

    If you're using create-react-app, check the docs on how to define custom environment variables. You can use dotenv-webpack if you have a custom Webpack setup.

    The code becomes

    const url = `${process.env.API_URL}/${props.match.params.id}`