How to use a Postgres db on heroku with Axios and Vue? - node.js

I making a spa with Vue and want to deploy this on Heroku and provision a database with Postgres.
I managed to get the app to run on Heroku, with a node server. I added the db and the connection (in the same file) and it is working in production.
But I want to make the HTTP-request to de the db with Axios and test this locally before deployment. And this is where I'm stuck.
I've copied the DATABASE_URL the a .env, but still no access to the database. When I print the value to the console it is always undefined.
My server.js:
const express = require("express");
const serveStatic = require("serve-static");
const path = require("path");
const port = process.env.PORT || 8080;
// Connection to the database
const { Client } = require('pg');
const client = new Client({
connectionString: process.env.DATABASE_URL,
ssl: {
rejectUnauthorized: false
}
});
client.connect();
client.query('SELECT table_schema,table_name FROM information_schema.tables;', (err, res) => {
if (err) throw err;
for (let row of res.rows) {
console.log(JSON.stringify(row));
}
client.end();
});
//
const app = express();
//here we are configuring dist to serve app files
app.use("/", serveStatic(path.join(__dirname, "/dist")));
// this * route is to serve project on different page routes except root `/`
app.get(/.*/, function (req, res) {
res.sendFile(path.join(__dirname, "/dist/index.html"));
});
app.listen(port);
console.log(`app is listening on port: ${port}`);
UserService.js:
import axios from 'axios';
// the single Axios instance we use for calls
const apiClient = axios.create({
//baseURL: 'http://localhost:5000',
baseURL: process.env.DATABASE_URL, // with ssl?
withCredentials: false, // this is the default
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
});
export default {
/* with pagination */
getUsers() {
console.log(process.env.DATABASE_URL);
return apiClient.get('/users');
},
};
package.json:
{
"name": "test-deploy-heroku",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint",
"start": "node server.js"
},
"dependencies": {
"axios": "^0.21.1",
"core-js": "^3.6.5",
"dns": "^0.2.2",
"express": "^4.17.1",
"pg": "^8.5.1",
"pg-native": "^3.0.0",
"vue": "^2.6.11",
"vue-router": "^3.2.0",
"vuetify": "^2.4.0",
"vuex": "^3.4.0"
},
"devDependencies": {
"#vue/cli-plugin-babel": "~4.5.0",
"#vue/cli-plugin-eslint": "~4.5.0",
"#vue/cli-plugin-router": "~4.5.0",
"#vue/cli-plugin-vuex": "~4.5.0",
"#vue/cli-service": "~4.5.0",
"#vue/eslint-config-prettier": "^6.0.0",
"babel-eslint": "^10.1.0",
"eslint": "^6.7.2",
"eslint-plugin-prettier": "^3.3.1",
"eslint-plugin-vue": "^6.2.2",
"prettier": "^2.2.1",
"sass": "^1.32.0",
"sass-loader": "^10.0.0",
"vue-cli-plugin-vuetify": "~2.3.1",
"vue-template-compiler": "^2.6.11",
"vuetify-loader": "^1.7.0"
}
}
I copied the config vars to my local .env file
heroku config:get CONFIG-VAR-NAME -s >> .env
And the started the process with
heroku local
But I still can not connect to the db with axios.
I searched all over, but didn't find an answer.

You may need to add require('dotenv').config() to the top of your server.js file
if (process.env.NODE_ENV === 'development') require('dotenv').config()

Related

TypeError: app.address is not a function - Shopify App Node.js

The issue is already describe here
Mocha API Testing: getting 'TypeError: app.address is not a function'
Tried to test my Shopify app using Mocha, Chai created with Nextjs. Tried several workarounds mentioned on the above link. But it still produces the following error
GET requests
GET /customers
1) Success should return true
0 passing (1s)
1 failing
1) GET requests
GET /customers
Success should return true:
TypeError: app.address is not a function
at serverAddress (node_modules\chai-http\lib\request.js:282:18)
at new Test (node_modules\chai-http\lib\request.js:271:53)
at Object.obj.<computed> [as get] (node_modules\chai-http\lib\request.js:239:14)
at Context.<anonymous> (test\appTest.js:44:10)
at processImmediate (node:internal/timers:466:21)
apptest.js
let chai = require("chai");
let chaiHttp = require("chai-http");
const server = require("../server/index");
chai.should();
chai.use(chaiHttp);
describe("GET requests", () => {
describe("GET /customers", () => {
it("Success should return true", (done) => {
chai.request(server)
.get("/customers")
.end((err, res) => {
console.log('Error => ', err);
console.log('Response => ', res);
res.body.success.should.equal(true)
done();
});
});
});
});
server.js
import "#babel/polyfill";
import createShopifyAuth, { verifyRequest } from "#shopify/koa-shopify-auth";
import Shopify, { ApiVersion } from "#shopify/shopify-api";
import dotenv from "dotenv";
import "isomorphic-fetch";
import Koa from "koa";
import Router from "koa-router";
import next from "next";
const mongoose = require("mongoose");
dotenv.config();
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== "production";
const app = next({
dev,
});
const handle = app.getRequestHandler();
const AccessToken = {};
Shopify.Context.initialize({
API_KEY: process.env.SHOPIFY_API_KEY,
API_SECRET_KEY: process.env.SHOPIFY_API_SECRET,
SCOPES: process.env.SCOPES.split(","),
HOST_NAME: process.env.HOST.replace(/https:\/\/|\/$/g, ""),
API_VERSION: ApiVersion.January22,
//API_VERSION: ApiVersion.October20,
IS_EMBEDDED_APP: true,
// This should be replaced with your preferred storage strategy
SESSION_STORAGE: new Shopify.Session.MemorySessionStorage(),
});
const ACTIVE_SHOPIFY_SHOPS = {};
app.prepare().then(async () => {
const server = new Koa();
const router = new Router();
server.keys = [Shopify.Context.API_SECRET_KEY];
server.use(
createShopifyAuth({
async afterAuth(ctx) {
// Access token and shop available in ctx.state.shopify
const { shop, accessToken, scope } = ctx.state.shopify;
AccessToken["access_token"] = accessToken;
ctx.cookies.set("accessToken", accessToken, {
httpOnly: false,
secure: true,
sameSite: "none",
});
ctx.cookies.set("shop_name", shop, {
secure: true,
sameSite: "none",
httpOnly: false,
});
const host = ctx.query.host;
ACTIVE_SHOPIFY_SHOPS[shop] = scope;
ctx.cookies.set("HOST", host, {
secure: true,
sameSite: "none",
httpOnly: false,
});
//Database Connection
const shopName = shop.replace("myshopify.com", "");
const formattedShopName = shopName
.replace(/[^a-z\d\s]+/gi, "")
.replace(/\s+/g, "")
.toLowerCase();
const connectionStr = `${process.env.CONNECTION_STRING}${formattedShopName}`;
await mongoose
.connect(connectionStr, {
// creds
})
.then(async () => {
console.log("database connected");
})
.catch((err) => console.log(err));
// Redirect to app with shop parameter upon auth
ctx.redirect(`/?shop=${shop}&host=${host}`);
},
})
);
router.get("/customers", async (ctx, next) => {
// Logics to fetch customers
});
const handleRequest = async (ctx) => {
await handle(ctx.req, ctx.res);
ctx.respond = false;
ctx.res.statusCode = 200;
};
router.get("(/_next/static/.*)", handleRequest); // Static content is clear
router.get("/_next/webpack-hmr", handleRequest); // Webpack content is clear
router.get("(.*)", verifyRequest(), handleRequest);
server.use(router.allowedMethods());
server.use(router.routes());
server.listen(port, () => {
console.log(`> Ready on http://localhost:${port}`);
});
});
index.js
require("#babel/register")({
presets: ["#babel/preset-env"],
ignore: ["node_modules"],
compact: false,
});
// Import the rest of our application.
module.exports = require("./server.js");
package.json
{
"name": "shopify-app-node",
"version": "1.0.0",
"description": "Shopify's node app for CLI tool",
"scripts": {
"lint": "next lint",
"test": "mocha",
"dev": "cross-env NODE_ENV=development nodemon ./server/index.js --watch ./server/index.js",
"build": "NEXT_TELEMETRY_DISABLED=1 next build",
"start": "cross-env NODE_ENV=production node ./server/index.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/Shopify/shopify-app-node.git"
},
"author": "Shopify Inc.",
"license": "MIT",
"bugs": {
"url": "https://github.com/shopify/shopify-app-node/issues"
},
"dependencies": {
"#babel/core": "7.12.10",
"#babel/polyfill": "^7.6.0",
"#babel/preset-env": "^7.12.11",
"#babel/register": "^7.12.10",
"#shopify/app-bridge-react": "^2.0.6",
"#shopify/app-bridge-utils": "^2.0.6",
"#shopify/dates": "^1.1.5",
"#shopify/koa-shopify-auth": "^5.0.3",
"#shopify/polaris": "^6.2.0",
"#szhsin/react-menu": "^3.0.1",
"apollo-boost": "^0.4.9",
"axios": "^0.26.0",
"cross-env": "^7.0.3",
"date-fns": "^2.28.0",
"dotenv": "^8.6.0",
"fs": "^0.0.1-security",
"graphql": "^14.5.8",
"isomorphic-fetch": "^3.0.0",
"jquery": "^3.6.0",
"koa": "^2.13.1",
"koa-router": "^10.0.0",
"koa-session": "^6.1.0",
"mdb-react-ui-kit": "^3.0.0",
"moment": "^2.29.1",
"mongodb": "^4.5.0",
"mongoose": "^6.2.9",
"next": "^12.0.8",
"next-env": "^1.1.1",
"node-fetch": "^2.6.1",
"path": "^0.12.7",
"react": "^17.0.2",
"react-apollo": "^3.1.3",
"react-beautiful-dnd": "^13.1.0",
"react-csv": "^2.2.2",
"react-data-table-component": "^7.4.7",
"react-datepicker": "^4.7.0",
"react-dnd": "^16.0.1",
"react-dnd-html5-backend": "^16.0.1",
"react-dom": "^17.0.2",
"react-moment": "^1.1.1",
"react-router": "^6.2.2",
"react-router-dom": "^6.2.2",
"react-table": "^7.7.0",
"read-json-lines-sync": "^2.2.0",
"recharts": "^2.1.9",
"rsuite": "^5.7.1",
"styled-components": "^5.3.5",
"url": "^0.11.0",
"webpack": "^5.70.0"
},
"devDependencies": {
"#babel/plugin-transform-runtime": "^7.12.10",
"#babel/preset-stage-3": "^7.0.0",
"#wojtekmaj/enzyme-adapter-react-17": "^0.6.6",
"babel-jest": "26.6.3",
"babel-register": "^6.26.0",
"chai": "^4.3.6",
"chai-http": "^4.3.0",
"enzyme": "3.11.0",
"eslint": "^8.9.0",
"eslint-config-next": "^12.0.10",
"husky": "^4.3.6",
"jest": "26.6.3",
"lint-staged": "^10.5.4",
"mocha": "^10.0.0",
"nodemon": "^2.0.7",
"prettier": "2.2.1",
"react-addons-test-utils": "15.6.2",
"react-test-renderer": "16.14.0",
"supertest": "^6.2.4"
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.{js,css,json,md}": [
"prettier --write"
]
}
}

Cannot GET / MERN stack deployment on heroku

Hi i am having trouble when trying to deploy my mern stack to heroku. every way i have tried to deploy it i get the same error of get the error Cannot GET /. i have gone through the tutorials but still no luck
this is my server. js file
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const passport = require("passport");
const users = require("./routes/api/users");
const payees = require("./routes/api/payees");
const transactions = require("./routes/api/transactions");
const path = require('path')
const app = express();
// Bodyparser middleware
app.use(
bodyParser.urlencoded({
extended: false
})
);
app.use(bodyParser.json());
// DB Config
const db = require("./config/keys").mongoURI;
// Connect to MongoDB
mongoose
.connect(
db,
{ useNewUrlParser: true }
)
.then(() => console.log("MongoDB successfully connected"))
.catch(err => console.log(err));
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(bodyParser.json());
// Passport middleware
app.use(passport.initialize());
// Passport config
require("./config/passport")(passport);
// Routes
app.use("/api/users", users);
app.use("/api/payees", payees);
app.use("/api/transactions", transactions)
if(process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, 'client', 'build')));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'client', 'build', 'index.html'))
});
}
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server up and running on port ${port} !`));
module.exports = { app };
and this is my package.json file
{
"name": "STUBANK",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"client-install": "npm install --prefix client",
"start": "node server.js",
"server": "nodemon server.js",
"client": "npm start --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\"",
"test": "mocha",
"heroku-postbuild": "cd client && npm install && npm run build"
},
"author": "Ojini Jude",
"license": "MIT",
"dependencies": {
"#material-ui/core": "^4.11.2",
"axios": "^0.21.1",
"bcryptjs": "^2.4.3",
"body-parser": "^1.18.3",
"chai": "^4.2.0",
"chai-http": "^4.3.0",
"classnames": "^2.2.6",
"crypto-random-string": "^3.3.0",
"dotenv": "^6.2.0",
"express": "^4.16.4",
"is-empty": "^1.2.0",
"jsonwebtoken": "^8.5.1",
"jwt-decode": "^3.1.2",
"mdbreact": "^5.0.1",
"mocha": "^8.2.1",
"mongoose": "^5.3.6",
"particles-bg": "^2.5.0",
"passport": "^0.4.1",
"passport-jwt": "^4.0.0",
"password-validator": "^5.1.1",
"react": "^17.0.1",
"react-bootstrap": "^1.4.0",
"react-dom": "^17.0.1",
"react-dropdown": "^1.9.0",
"react-redux": "^7.2.2",
"react-router-dom": "^5.2.0",
"react-scripts": "^4.0.1",
"react-search-box": "^2.0.2",
"react-search-field": "^1.2.0",
"react-select": "^3.1.1",
"redux": "^4.0.5",
"redux-thunk": "^2.3.0",
"supertest": "^6.0.1",
"validator": "^13.5.1"
},
"devDependencies": {
"concurrently": "^4.1.2",
"nodemon": "^1.19.4"
},
"engines": {
"node": "12.16.0"
}
}
Any help would be greatly appreciated.
file structure

front end not being deployed in Heroku

I'm trying to deploy my first MERN website to heroku. I have been following different tutorials but I am having trouble connecting the front end with the back end, although they connect fine in development mode.
Just to clarify: the only one that is bein deployed is the server side. I am not being able to deploy the front end.
client's package.json proxy:
"proxy": "http://localhost:5000"
Server package.json:
{
"name": "pictshare",
"version": "1.0.0",
"description": "Image Sharing Application",
"main": "server.js",
"scripts": {
"start": "node server.js",
"server": "nodemon server",
"build": "cd client && npm run build",
"install-client":"cd client && npm install",
"heroku-postbuild":"npm run install-client && npm run build",
"client": "npm start --prefix client",
"dev": "concurrently -n 'server,client' -c 'red, green' \"npm run server\" \"npm run client\""
},
"author": "",
"license": "MIT",
"dependencies": {
"bcryptjs": "^2.4.3",
"body-parser": "^1.19.0",
"config": "^3.3.1",
"ejs": "^3.0.2",
"express": "^4.17.1",
"express-validator": "^6.4.0",
"form-data": "^3.0.0",
"gravatar": "^1.8.0",
"gridfs-stream": "^1.1.1",
"jsonwebtoken": "^8.5.1",
"merge-images": "^1.2.0",
"method-override": "^3.0.0",
"moment": "^2.24.0",
"mongoose": "^5.9.7",
"multer": "^1.4.2",
"multer-gridfs-storage": "^4.0.2",
"node": "^13.12.0",
"nodemailer": "^6.4.6",
"path": "^0.12.7",
"react-draggable": "^4.2.0",
"request": "^2.88.2"
},
"devDependencies": {
"concurrently": "^5.1.0",
"minimist": "^1.2.5",
"nodemon": "^2.0.2"
}
}
Server.js:
const express = require('express');
const connectDB = require('./config/db');
const app = express();
const bodyParser = require('body-parser')
connectDB();
//Initialize Middleware
app.use(express.json({ extended: false }));
app.use(bodyParser.urlencoded({ extended: false }))
app.get('/', (req, res) => res.send('API Running'));
...
app.use('/api/posts', require('./routes/api/posts'));
if (process.env.NODE_ENV === 'production'){
app.use(express.static('client/build'))
}
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
Mongoose:
const mongoose = require('mongoose');
const config = require('config');
const db = process.env.MONGODB_URI || config.get('mongoURI');
const connectDB = async () => {
try {
await mongoose.connect(db, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true,
useNewUrlParser: true,
});
console.log('MongoDB Connected...');
} catch(err) {
console.error(err.message);
process.exit(1);
}
}
module.exports = connectDB;
I really appreciate any ideas or points of views!!
Thank you so much everyone!
Maybe you already did the job, let me point out a thing here in your code:
app.use(express.static('client/build'))
you maybe need to put like this :
const app = express();
const path = require('path');
app.use('/static', express.static(path.join(`${__dirname}/client/build`)));
then just send the file when the server is online:
app.get('/*', (req, res) => {
res.sendFile(path.join(`${__dirname}/client/build/`));
});
If you have .env file. Try adding this NODE_ENV = production in it.

Trying to send simple data from server to react native client-side

I am trying to send data from server.js using express and node.js to my client-side which is in React Native, both sides work individually but aren't communicating with each other. I am fairly new to backend development so I am beginning to understand how it functions and how to implement required behaviors. Please can anyone help?
server.js
const express = require('express')
const app = express()
const port = process.env.PORT || 5000;
app.get('/', (req, res) => {
res.send({ express: 'YOUR EXPRESS BACKEND IS CONNECTED TO REACT' })
}
)
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
app.js
import React, { Component } from "react";
import {Modal, StyleSheet, View, StatusBar,Text, ActivityIndicator, FlatList} from 'react-native'
export default class FetchExample extends React.Component {
constructor(props){
super(props);
this.state = {
data: ''
};
}
componentDidMount() {
// Call our fetch function below once the component mounts
this.callBackendAPI()
.then(res => this.setState({ data: res.express }))
.catch(err => console.log(err));
}
// Fetches our GET route from the Express server. (Note the route we are fetching matches the GET route from server.js
callBackendAPI = async () => {
const response = await fetch('/');
const body = await response.json();
if (response.status !== 200) {
throw Error(body.message)
}
return body;
};
render(){
return(
<View style={{flex: 1, paddingTop:20}}>
<Text>{this.state.data}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
},
});
package.Json
{
"name": "mapp",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest"
},
"dependencies": {
"#expo/vector-icons": "^10.0.2",
"babel-plugin-mobx-deep-action": "^1.6.1",
"express": "^4.17.1",
"jetifier": "^1.6.3",
"jsc-android": "241213.x.x",
"mobx": "^5.11.0",
"mobx-react": "^6.1.1",
"native-base": "^2.13.8",
"react": "16.8.3",
"react-native": "^0.59.10",
"react-native-background-fetch": "^2.6.0",
"react-native-background-geolocation": "^3.0.7",
"react-native-css-gradient": "^0.3.1",
"react-native-drop-down-item": "^1.0.5",
"react-native-dropdown-menu": "^2.0.0",
"react-native-elements": "^1.2.6",
"react-native-gesture-handler": "^1.3.0",
"react-native-input-scroll-view": "^1.9.3",
"react-native-ionicons": "^4.5.6",
"react-native-linear-gradient": "react-native-community/react-native-linear-gradient",
"react-native-maps": "^0.24.2",
"react-native-responsive-screen": "^1.2.2",
"react-native-svg": "^9.5.2",
"react-native-svg-transformer": "^0.13.0",
"react-native-vector-icons": "^6.5.0",
"react-native-vertical-tab-view": "^0.1.3",
"react-navigation": "^3.11.0",
"react-redux": "^7.1.0",
"redux": "^4.0.1"
},
"devDependencies": {
"#babel/core": "7.4.5",
"#babel/plugin-proposal-decorators": "^7.4.4",
"#babel/runtime": "7.4.5",
"babel-jest": "24.8.0",
"babel-preset-react-native": "4.0.0",
"jest": "24.8.0",
"metro-react-native-babel-preset": "0.54.1",
"react-test-renderer": "16.8.3",
"redux-devtools": "^3.5.0"
},
"jest": {
"preset": "react-native"
},
"proxy": "http://localhost:5000/"
try updating the url to the full url of your local server:
const response = await fetch('http://localhost:5000');
Check the port matches your express server port ^^

I get 404 error in the localhost even though I already did "npm run build"

I'm trying to send a small demo made with React to production. I did not make the demo with create-react-app, I did it by hand. I used express.js to serve the application.
When I run the command "SET NODE_ENV = production node server.js" (I'm in Windows, that's why SET) and I go to the localhost I keep getting GET / 404, even though I already made the command "npm run build".
Since it's the first time I do this, I really have no clue what happens.
This is my package.json:
{
"name": "app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack --colors",
"serve": "webpack-dev-server --content-base build/ --color --
progress",
"start": "npm run build && npm run serve",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Pepe",
"license": "MIT",
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.0",
"babel-eslint": "^8.2.2",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.4.0",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"css-loader": "^0.28.9",
"eslint": "3.15.0",
"eslint-config-airbnb": "14.1.0",
"eslint-loader": "^1.9.0",
"eslint-plugin-import": "2.2.0",
"eslint-plugin-jsx-a11y": "4.0.0",
"eslint-plugin-react": "6.10.0",
"extract-text-webpack-plugin": "^3.0.2",
"html-webpack-plugin": "^2.30.1",
"identity-obj-proxy": "^3.0.0",
"jshint": "^2.9.6",
"style-loader": "^0.20.2",
"url-loader": "^0.5.8",
"webpack": "^3.3.0",
"webpack-dev-server": "^2.9.7"
},
"dependencies": {
"bootstrap": "^4.0.0",
"compression": "^1.7.3",
"express": "^4.16.4",
"mime": "^1.4.1",
"morgan": "^1.9.1",
"normalize.css": "^8.0.0",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-router-dom": "^4.1.1",
"uuid": "^3.2.1"
},
"standard": {
"ignore": [
"/build/"
]
},
"eslintConfig": {
"extends": [
"standard",
"standard-jsx"
]
},
"stylelint": {
"extends": "stylelint-config-standard"
},
"optionalDependencies": {
"win-node-env": "^0.4.0"
}
}
And here is my server.js:
const { createServer } = require('http');
const express = require('express');
const compression = require('compression');
const morgan = require('morgan');
const path = require('path');
const normalizePortprocess = port => parseInt(port, 10);
const PORT = normalizePortprocess(process.env.PORT || 3000);
const app = express();
const dev = app.get('env') !== 'production';
if (!dev) {
app.disable('x-powered-by');
app.use(compression());
app.use(morgan('common'));
app.use(express.static(path.resolve(__dirname, 'build')));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'build', 'index.html'));
});
}
if (dev) {
app.use(morgan('dev'));
}
const server = createServer(app);
server.listen(PORT, err => {
if(err) throw new err;
console.log(`Server listen in ${PORT}`);
});
Everything would seem to work correctly except that despite having executed to many times the command "npm run build", still nothing appears
You are running in a development environment, and only handling that GET request if !dev.
if (!dev) { // here is the problem
// ...
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'build', 'index.html'));
});
}
Instead, either remove the if statement and always handle this route, or change it to if(dev).

Resources