Morten
Morten

Reputation: 143

running frontend and backend on different ports

Hi Im running my frontend (create-react-app) and backend server (express.js) on different ports but on the same host. For example: frontend is on 127.0.0.1:3000 and backend on 127.0.0.1:3003.

in my package.json:

{...
 "proxy": "http://localhost:3003",
...}

Everything worked fine till I didn't migrate my app to remote server.

My app started to refresh unexpectedly when I'm trying to send http request (axios) to server (probably due to bad proxy settings).

So I have frontend app running on 35.125.320:10:3000 and server is running on 35.125.320:10:3003. My http requests was unexpectedly cancelled. (I checked the network ). So I changed my proxy settings to

{...
  "proxy": "35.125.320:10:3003",
...} 

but anyway my app is still refreshing when Im trying to make http req. on server. I think the problem is that I can't reach my express backend server. So proxy is forwarding my requests badly.

UPDATE

scenario:(Im doing two post requests)

1) first request still passed (app is not refreshed)

2) same request passed (but sometimes app is refreshed)

3) second is still cancelled by browser.

QUESTION

How can my frontend communicate with backend server via proxy when they are running on different ports but on the same server and domain ??

Thanks for the answer.

Upvotes: 3

Views: 3949

Answers (2)

Morten
Morten

Reputation: 143

Solution:

The problem was that I used proxy in production that is only suitable for development.

I added this line in my express.js server :

app.use(express.static(`${process.cwd()}/build`));
app.use(express.static(`${process.cwd()}/public`));

I make a build and serve js,css files from my build folder. And also I needed serve static files (images, folders, etc...) from my public folder.

This problem can also cause cancelling http request by browser on production. Means, requests weren't able to reach server.

Upvotes: 1

Danny Harding
Danny Harding

Reputation: 1745

To make your app publicly available, you will want to make a production build. You mentioned in a comment that you "run npm build and then serve this build as static file in express.js". This is a great way to make your react app publicly available. As it says in the create-react-app documentation:

npm start or yarn start

Runs the app in development mode.

When running yarn start or npm start, you are also given a notification that says "Note that the development build is not optimized." The best option will be to run yarn build or npm build and find a way to serve those static files as you are doing.

Upvotes: 0

Related Questions