Skip to content
Permalink
Browse files

Connect back&front apps, serve React build from Express

* Fetch data from the backend in frontend app
* Serve the React production build from the Express app
  • Loading branch information...
bhubr committed Aug 31, 2019
1 parent 7dd4948 commit 2b224ec6871675936fb02a53969c7e93d3d361ad
@@ -4,6 +4,10 @@
"main": "index.js",
"author": "Benoit Hubert <benoithubert@gmail.com>",
"license": "MIT",
"scripts": {
"lint": "lerna run lint --stream",
"start": "lerna run start --stream"
},
"devDependencies": {
"husky": "^3.0.4",
"lerna": "^3.16.4"
@@ -1,10 +1,25 @@
// src/app.js
import express from 'express';
import bodyParser from 'body-parser';
import path from 'path';

// Check whether we are in production env
const isProd = process.env.NODE_ENV === 'production';

const app = express();
app.use(bodyParser.json());

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

if (isProd) {
// Compute the build path and index.html path
const buildPath = path.resolve(__dirname, '../../front/build');
const indexHtml = path.join(buildPath, 'index.html');

// Setup build path as a static assets path
app.use(express.static(buildPath));
// Serve index.html on unmatched routes
app.get('*', (req, res) => res.sendFile(indexHtml));
}

module.exports = app;
@@ -3,10 +3,10 @@ import request from 'supertest';
import app from '../src/app';

describe('app', () => {
it('GETs / and should obtain { foo: "bar" }', async () => {
it('GETs /api/foo and should obtain { foo: "bar" }', async () => {
expect.assertions(1);
const res = await request(app)
.get('/')
.get('/api/foo')
.expect(200);
expect(res.body).toMatchInlineSnapshot(`
Object {
@@ -68,5 +68,6 @@
"yarn lint",
"git add"
]
}
},
"proxy": "http://localhost:5000"
}
@@ -1,9 +1,22 @@
import React from 'react';
import React, { useState, useEffect } from 'react';

function App() {
const [foo, setFoo] = useState('N/A');
useEffect(
() => {
fetch('/api/foo')
.then((res) => res.json())
.then((data) => setFoo(data.foo))
.catch((err) => setFoo(err.message));
},
);
return (
<div>
<h1>Hello World</h1>
<p>
Server responded with foo:
{foo}
</p>
</div>
);
}

0 comments on commit 2b224ec

Please sign in to comment.
You can’t perform that action at this time.