skip to Main Content

I have a React + Express app that is fetching the data normally when on localhost.
On public domain, React app loads, but it throws this error on my fetch requests "Failed to load resource: net::ERR_CONNECTION_REFUSED".

Also I don’t know if this is relevant, but the screen is blank when no port number or port number 443 in Axios request URL is put, but when I put 80 or 8080, the site loads.

My backend and frontend are on the same URL, that could also be the problem, even though I have seen that it is possible to have both on the same URL.

Please help because I’m not sure if I have messed up somewhere in my code, or in cPanel setup of the Node.js app.

I tried testing through Postman, and it returns me the HTML of my React application instead of the data from my database.

I have also tried downgrading Node.js version in the application setup and it’s not working.

2

Answers


  1. Sounds like there are two issues.

    1. Your API tests should return the data, not a webpage. Check the configuration to ensure traffic to domain.com/your-api-name is actually routed to the port with nodejs running.

    2. The Connection refused error could be a CORS issue. Try adding the following code to your index.js file, above app.use().

      const cors = require("cors");
      app.use(cors());

    then, inside an app.use() method, include the following:

    app.use((req, res, next) => {
      const allowedOrigins = [
        
        "http://your-domain-name.com",
      ];
      const origin = req.headers.origin;
    
      allowedOrigins.includes(origin) &&
        res.setHeader("Access-Control-Allow-Origin", origin);
    
      // Request methods you wish to allow
      res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
    
      // Request headers you wish to allow
      res.setHeader("Access-Control-Allow-Headers", "content-type");
    
      // Set to true if you need the website to include cookies in the requests sent
      // to the API (e.g. in case you use sessions)
      res.setHeader("Access-Control-Allow-Credentials", true);
    
      // Pass to next layer of middleware
      next();
    });
    

    This allows requests to be made from your api, from your domain name.

    Login or Signup to reply.
  2. If on 443 it does not work it means you have not setup ssl certificate for your domain

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search