Chappie
Chappie

Reputation: 21

Nodejs : how to redirect subdomains to ports?

I'm creating a fullstack web-app with an API as backend, and I'm hosting it on a DigitalOcean server.

The front-end (reactjs) is running on a port (3000) and the backend (express server -RESTFul API-) on another (3001).

I would like to be able to communicate with both of them from a single domain.

Ex :

How can I do this ?

I've already tried some things :

I don't really want to put frontend and backend in the same running server (same port)

I'm quite new in mastering servers so I don't kown nothing, sorry.

Thanks for the help.

PS: I'm french, so sorry for the bad English :)

Upvotes: 2

Views: 1295

Answers (1)

Poulpy
Poulpy

Reputation: 134

Hello since i dont have that much information i will stay general. What you want is a reverse proxy. You can use http-proxy-middleware: https://www.npmjs.com/package/http-proxy-middleware.

Let's say you run your frontend on http://example.com:3000 and your backend on http://example.com:3001.

Now lets say you want http://example.com:3001/42-is-the-answer to point to http://example.com:3000 (You can add a path if you want).

The only thing to do would be to use a proxy on the server instance of example.com:3001 like so:

const proxy = require("http-proxy-middleware");
const app = express();
....
app.use(    proxy("/42-is-the-answer", {
  target: "http://example.com:3000/"
}))

Now if you access http://example.com:3001/42-is-the-answer, the request will be proxied to http://example.com:3000.

I hope this helps.

Upvotes: 0

Related Questions