Getting started React with Express server

Goal

Create React app with express server

Step 1: Initialise package.json and add packages

1
2
3
npm init -y
yarn global add nodemon
yarn add express concurrently

Step 2: Create a server.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// server.js
const express = require('express');
const port = 1234;
const app = express();

const customers = [
{ id: 1, name: 'hoe' },
{ id: 2, name: 'fua' },
{ id: 3, name: 'piyo' }
];

app.get('/api/customers', (req, res) => {
res.json(customers);
});

app.listen(port, () => console.log(`😃 Server listening on port ${port}`));

Test

1
nodemon server.js

Open browser and go to http://localhost:1234/api/customers

api_customers

Step 3: Create client with React

1
npx create-react-app client

Step 4: Update package.json file both root and in client directory

1
2
3
4
5
6
// package.json (root)
"scripts": {
"server": "nodemon server.js",
"client": "cd ./client && yarn start",
"start": " concurrently \"yarn server\" \"yarn client\" "
},
1
2
// package.json (root)
"proxy": "http://localhost:1234/"

Step 5: Update App.js to get data from server.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import React, { useState, useEffect } from 'react';
import './App.css';

function App() {
const [customers, setCustomers] = useState([]);

useEffect(() => {
fetch('api/customers')
.then(res => res.json())
.then(data => {
setCustomers(data);
});
}, []);

return (
<div className='App'>
<header className='App-header'>
<div>customers</div>
{customers.map(x => (
<div key={x.id}>{x.name}</div>
))}
</header>
</div>
);
}

export default App;

Step 6: Run server and client

1
yarn start

result