Home > Enterprise >  React app can't reach my express app in production with its requests but works fine in developm
React app can't reach my express app in production with its requests but works fine in developm

Time:07-20

I'm trying to send a simple get request to my express backend at the mywebsite.com/test route. The server should respond with {"test": "test"}. This works fine in development on localhost, but no matter what I try in a production environment I can't get a response back from my server. I'm hosting this website on a GoDaddy VPS with CentOS 7. The react app loads just fine on live, but any requests I make return a html document with a tag saying "You need to enable JavaScript to run this app". (I'm seeing this in the response section of the network tab in chrome devtools)

I've run the backend with node from ssh and it says its listening on port 5000. I have added a proxy to package.json, as well as a homepage as such:

  "proxy": "http://localhost:5000",
  "homepage": "."

I've tried having the homepage field be http://mywebsite.com as well with no results.

Here is my express app setup:

const express = require('express');
const PORT = process.env.PORT || 5000;
const app = express();
app.use(express.json());

app.get('/', function(req, res) {
   res.status(200).send()
});

app.get('/test', (req, res) => {
    res.status(200).json({test: "test"});
})

app.listen(PORT, async function() {
    console.log(`Listening on Port ${PORT}`);
});

In development I receive this in the network tab as expected:

{"test":"test"}

I'm at a complete loss at this point, it feels like I've tried everything.

CodePudding user response:

Solved. It turns out my issue was in my .htaccess file.

I understand I shouldn't use .htaccess if I have a VPS, but being quite new to dealing with a VPS, this was my issue:

<IfModule mod_rewrite.c>
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-l
  RewriteRule . /index.html [L]
</IfModule>

I had this added due to an issue with our React Router. This solved that problem, but consequentially rewrote all of my backend requests. After removing this, I managed to add this rule: (from: I have Godaddy Shared Web Hosting I need to host node.js website can host site?)

RewriteRule (.*) http://localhost:5000/$1 [P,L]
DirectoryIndex index.html

Which allowed everything to work again.

  • Related