How to connect node.js back-end and react.js front-end on cPanel?

Viewed 364

I have a frontend built with React and a backend built with Node JS and Express. I am hosting the site with cPanel.

The files from the React build are located in the home/public_html directory and the files of the backend are located in home/server directory.

-home
  --public_html
    ---index.html
    ---// *rest of the frontend files*
  --server
    ---server.js
    ---api
    --- // *rest of the backend files*

In the public_html directory I added a .htaccess file with the following code

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

that from my understanding should set the server/server.js as the entry point.

(Is this syntax correct?)

In my server.js file I set the following:

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

which is supposed to serve the static files from the pubic_html folder.

When I am loading my site, I see the frontend being served but any request to the API responses with a 400 status code.

In my axios configurations, I am setting

const BASE_URL = process.env.NODE_ENV === "production" ? "/api/" : "//localhost:3030/api/";

which is the way I used to upload sites to Heroku. It resolves with http://www.example.com/api/ The problem is that on cPanel the http://www.example.com/ is set as the public_html directory. I need to make the BASE_URL go back up on the path to the server directory.

So my questions are: How do I set on axios to go back to the server directory? OR Should I put my server directory inside the public_html directory? If so, isn’t it a security risk to allow people to navigate inside my server directory and access sensitive content?

I will appreciate any help! Thanks.

0 Answers
Related