ocram
ocram

Reputation: 1434

create-react-app with Express

I need to query a database and I'm using create-react-app. The library to connect to the DB (pg-promise) does not work with Webpack and needs to be running on a Node server.

So I installed Express and have this:

app.get('*', (req, res) => {
  res.sendFile(path.resolve(__dirname, '..', 'build', 'index.html'));
})

How can I load data from the database from the React pages? I though of using request but how can I make a request to my own server? And what should I add to the lines of code above? I think it would be something like:

app.get('/query/:querybody', (req, res) => {
  // process and return query
})

Is this right? How can I make it work with a SPA?

Upvotes: 1

Views: 234

Answers (2)

vsenko
vsenko

Reputation: 1149

On the server side you are going in the correct direction: you need to setup endpoint which will respond with data based on request. In you example you setup an endpoint for a GET HTTP request. If you will need to pass a complex request (for example add new record to database), consider using POST HTTP requests.

On the client side (in the browser) you will need a library that will assist you in sending requests to your server. I can recommend to try Axios (https://github.com/mzabriskie/axios). Usually if you omit protocol, server name and port, request will be sent to the server from which the page was loaded: http:127.0.0.1:8001/api/endpoint => /api/endpoint

Upvotes: 0

rossipedia
rossipedia

Reputation: 59367

Probably the most friction-free method would be to have a separate app.js or server.js along side your CRA application. You can use a tool like concurrently to run both your React app and the express app.

The trick is to serve your express app on a different port than the default :8080 that CRA serves on. Usually 8081 is a good choice, as it's a common convention to use port numbers that are close together when developing.

In your React app, you will need to make sure you use the full URL for the express endpoint: http://localhost:8081/query/...

Upvotes: 1

Related Questions