Home > database >  Communicating with React and Express without using localhost to view from another machine
Communicating with React and Express without using localhost to view from another machine

Time:08-07

I have an application that runs fine when viewing the application from your local machine/vm, but if I start the application in a vm and try to access the application using {vm-IP:PORT}, Express and React are not able to communicate with each other.

How React communicates -

  const api = axios.create({
    baseURL: "http://localhost:5000"
  })

How Express communicates -

router.use(cors({
    origin: 'http://localhost:3000'
}))

I would have to hard code the ip address of the machine into the code to have them communicate correctly (replace localhost with ip), but that would also mean the application would have to be edited every time it is ran on a different machine.

Is there a workaround to this issue? The application is also dockerized, so I don't mind being able to paste a ip address in the docker-compose so that React and Express can communicate but I'm not sure if that's possible.

CodePudding user response:

You can use ngrok for this issue. refer this doc: https://ngrok.com/docs

Basically what ngrok does is that it will allow you to serve your port on internet without actually hosting it. It is very easy to use. First install ngrok to your system and then run ngrok http 5000 command in your terminal to server your express port 5000 on internet. ngrok will allow you to serve your port on internet for 8 hours after that ngrok url will be deactivated. Running above command will give you one url which you can use as below in your react application

const api = axios.create({
    baseURL: <<url_generated_by_ngrok>>
  })

CodePudding user response:

According to the documentation

app.use(cors({origin: true}));

will accept every origin and set a corresponding Access-Control-Allow-Origin header. That is better than setting Access-Control-Allow-Origin: *, which browsers do not accept when credentials are involved.

If accepting every origin is too broad, you can also implement rules in a function and use

app.use(cors({origin: myOriginFunction}));
  • Related