2
votes

So here is my issue in a pickle: btw I had some trouble finding out how to do this through google and I did try using StackOverflow but couldn't find the exact answer

So I have a ReactJS website where I use

yarn start

to run and it launches on localhost:3000 I want it to launch on localhost:3000 while an express server also launches on that server, aka start the react server up in express.js.

It seems like every tutorial I've found, most are outdated, and the remaining ones are guides to turn react into a static website and THEN use express. I would like to keep react on the server-side for advantage of react-router

Edit1: So basically when I have an expressjs server THE DATABASE DETAILS HAVE BEEN REMOVED, THAT LINE ISNT AN ERROR

const express = require('express'); var app = express();

var mysql = require('mysql'); var connection = mysql.createConnection({ host : database : 'main' });

connection.connect()

app.post('/users', function(req, res) { var user = req.body; res.end('Success'); })

app.listen(3000, function(){ console.log('Express sever is listening on port 3000') })

//connection.end()

I also start the create-react-app server with yarn start and it launches on localhost:3000 but this expressjs server overrides that.

So I want to connect the two to be able to send post requests

2
Is there a reason you can't run your express server on port 3001 and the react front end on port 3000? Doing that you can access the express server via "localhost:3001/users" to send the post request. - bluesixty
@bluesixty what if I put this on an AWS server? - adriam

2 Answers

4
votes

I just recently worked on a sample repo that implements this strategy. There are a few ways this can be done, but the simplest way to do this will be to start the express server as a second server that will run on a different port, ie. 3001. You can then use concurrently to launch both the react server (I am assuming webpack) and the express API server in a single command.

Here is a tutorial that shows how this can be set up. You should pay attention to the section in this tutorial about proxying requests from the client (browser) through the webpack server. There are some considerations to think about with regards to CORS configuration if you do not proxy requests through the webpack server.

Here is my proof of concept repo where I implemented just what you are looking for: react client, and express server. It can be run via concurrently or with docker (compose).

0
votes

You can change the port on which express is listening:

var server = app.listen(3001, function () {
    var host = server.address().address
    var port = server.address().port
    console.log("Example app listening at http://%s:%s", host, port)

Change 3001 to any valid port number