Changed the way app is run

Now Express serves React client/build directory as static files.
All unmatched requests are answered with index.html file.
This commit is contained in:
Maciej Krzyżanowski 2023-02-28 19:18:48 +01:00
parent 16825071b3
commit e9ad514166
3 changed files with 16 additions and 5 deletions

View File

@ -5,6 +5,7 @@ To start this application you need to:
- Setup some database and user with permissions to it
- Create .env file in the main directory and fill it in with fields DB_USER, DB_PASS, DB_HOST, DB_PORT and DB_NAME. In case of confusion you may check exemplary .env file saved as .env.example in the root directory of this repository.
2. Run both SQL scripts, which are located in the main directory. For app to be usable it is also recommended to insert some data to the database.
3. Run `npm start` in the main directory
4. Run `npm start` in the client/ directory
5. App will run on localhost:3000
3. Run `npm build` in the client directory.
4. Run `npm start` in the main directory
5. App will run on localhost:5000
Note: pm2 or/and nginx may be used to run this app for production

12
app.js
View File

@ -4,12 +4,13 @@ const session = require('express-session');
const responseTime = require('response-time');
const types = require('pg').types;
const validator = require('validator');
const path = require('path');
require('dotenv').config();
const app = express();
const db = pgp(`postgres://${process.env.DB_USER}:${process.env.DB_PASS}@${process.env.DB_HOST}:${process.env.DB_PORT}/${process.env.DB_NAME}`);
const port = 3001;
const port = 5000;
class Point {
x;
@ -43,6 +44,9 @@ types.setTypeParser(603, function(rectangleStr) {
return new Rectangle(lowerBottomPoint, size);
});
// Frontend hosting:
app.use(express.static(path.join(__dirname, 'client/build')));
app.use(session({
store: new (require('connect-pg-simple')(session))({
pgPromise: db,
@ -593,6 +597,12 @@ app.get('/simulate-logout', (req, res) => {
res.send(`Logged out!`);
});
// This should remain at the end of all routes
// It will direct every not matched route to index.html file
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, 'client/build', 'index.html'));
});
app.listen(port, () => {
console.log(`Skrytka.app słucha na porcie ${port}...`);
});

View File

@ -25,7 +25,7 @@
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"proxy": "http://localhost:3001",
"proxy": "http://localhost:5000",
"browserslist": {
"production": [
">0.2%",