I have a Front End application which is mainly based on React, and I have created a node server to serve the application. Build and everything are successful, and the the index.html is also served, but it doesn't read the environment variables that I set through heroku application settings (even from CLI).
Package.json scripts
"scripts": {
"start": "node server",
"start-dev": "react-scripts start",
"start-windows": "set PORT=3001 && react-scripts start",
"build": "react-scripts build",
"postinstall": "npm run build",
"test": "jest src/**/*.test.js",
"eject": "react-scripts eject"
}
node server,
const express = require ('express')
const app = express();
const http = require('http').Server(app);
const path = require( 'path')
let port = process.env.PORT || 3000;
app.use(express.static(path.join(__dirname, 'build')));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'build') + '/index.html');
});
app.listen(port, () => {
console.log(`App running on port ${port}`);
});
I print followings in a js,
console.log('LOCAL_TEST_ENVIRONMENT --- ', process.env.LOCAL_TEST_ENVIRONMENT) // LOCAL_TEST_ENVIRONMENT --- undefined
console.log('BACKEND_URL --- ', process.env.BACKEND_URL) // BACKEND_URL --- undefined
console.log('NODE_ENV --- ', process.env.NODE_ENV) // NODE_ENV --- production
Environment variables I set,
How can I fix this?
The prefix REACT_APP_ is necessary when accessing env variables, try
{process.env.REACT_APP_LOCAL_TEST_ENVIRONMENT}
Related
Everything works fine on local machine, Please let me if my server setup is correct
Project Structure
/client/--React frontend app
/client/package.json
/index.js
/package.json -- express server
In My /index.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require("path");
const app = express();
app.use(cors());
app.use(express.json());
if (process.env.NODE_ENV === "production") {
app.use(express.static("client/build"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
});
}
app.listen(process.env.B_PORT || 5000, () => {
console.log(`Express server Up and Running - Port : ${process.env.B_PORT}`);
});
In My /client/package.json
{
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"proxy": "http://localhost:5000",
}
I am getting 405 not allow for post request, but when i do http://myec2ip:5000 i can json response from express.
What config am i missing ?
You will need to open port 5000 in security group setting of ec2 and allow anyone to access it using 0.0.0.0 for incoming connections.
Trying to configure proxy in react native with node to run axios calls.
Tried the following code in server/package.json
"proxy": {
"/*": {
"target": "http://localhost:5000/"
}
},
"scripts": {
"start": "node index.js",
"server": "nodemon index.js",
"client": "cd ../client && yarn ios",
"dev": "concurrently \"yarn server\" \"yarn client\""
}
server/authRouter.js
const authRouter = require('express').Router();
authRouter.get('/test', (req, res) => {
res.send('proxy success');
});
module.exports = authRouter;
server/index.js
const express = require('express');
const authRouter = require('./authRouter');
const app = express();
app.use('/auth', authRouter);
const PORT = process.env.PORT || 5000;
app.listen(PORT);
client/app.js
await axios.get('/auth/test');
When I run yarn dev and test an axios call, it logs the following error
LOG [Error: Network Error]
any help would be much appreciated.
Try calling the proxy directly in axios
http://localhost:5000/auth/test
I'm not sure why it doesn't work that way, even i had a problem in the past.
I'm trying to upload an express/node.js app to heroku. The app is deployed succesfully but when I try to access the url I get error: Not Found.
When I run heroku logs --tail I get:
Error: ENOENT: no such file or directory, stat '/client/build/index.html'
so I think I'm doing something wrong with the directories and the statics folder
this is my server.js file:
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const passport = require("passport");
const cors = require("cors");
const path = require("path");
const users = require("./routes/api/users");
const profile = require("./routes/api/profile");
const matches = require("./routes/api/matches");
const app = express();
//body-parser middleware
app.use(bodyParser.urlencoded({ extended: false, limit: "50mb" }));
app.use(bodyParser.json({ limit: "50mb" }));
//db config
const db = require("./config/keys").mongoURI;
//cors
app.use(cors());
//connect to mongoose
mongoose
.connect(db, { useNewUrlParser: true })
.then(() => console.log("MongoDB connected"))
.catch(err => console.log(err));
//Passport middleware
app.use(passport.initialize());
app.use("/images", express.static(path.join(__dirname + "/images")));
//Passport config
require("./config/passport")(passport);
//Use route
app.use("/api/users", users);
app.use("/api/profile", profile);
app.use("/api/matches", matches);
//Serve static assets if in production
if (process.env.NODE_ENV === "production") {
app.enable("trust proxy");
//Set static folder
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 running on port ${port}`));
I also include an image of the folders "positions"
I solved this issue by defining build and install command in my package.json. Heroku would look for a build command for production in there.
"scripts": {
"build": "cd client && npm run build",
"install": "cd client && npm install",
"start": "node server",
"server": "nodemon server",
"client": "npm start --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\""
},
I think it should be like this
app.use("/images", express.static(path.join(__dirname, "images")));
Edit: Actually your app is expecting to find a file at /../client/build/index.html but that file does not exist (which is what ENOENT error means). So you either need to create the expected directory structure or else configure your application such that it looks in the correct directory for index.html. That whats i understand now, i hope this would help you.
I also got similar error. For me the problem is I have wrong script for build in package.json file, So build is not creating at all.
Verify you have "heroku-postbuild" script as below in package.json file.
"scripts": {
"start": "node server.js",
"server": "nodemon server.js",
"client": "npm start --prefix client",
"clientinstall": "npm install --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\"",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
},
Im trying to deploy a nodejs and react app to Heroku. It works completely fine local and it does serve my backend, but i get Not Found on anything else than my api endpoints. It seems like its not running the build script in the client folder. Can anyone help me spot where it goes wrong?
server.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const path = require('path');
const projects = require('./routes/api/projects');
const app = express();
// Body parser middlewaree
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// DB Config
const db = require('./config/keys').mongoURI;
// Connect to DB
mongoose
.connect(
db,
{ useNewUrlParser: true }
)
.then(() => console.log('mongoDB connected.'))
.catch(err => console.log(err));
// Setting up routes
app.use('/api/projects', projects);
// Serve static assets if in 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}`));
package.json
"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\"",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
},
I've deployed successfully to Heroku using the following code (I've just answered an alike question here):
app.use(express.static(path.join(__dirname, './client/build')))
app.get('*', function(_, res) {
res.sendFile(path.join(__dirname, './client/build/index.html'), function(err) {
if (err) {
res.status(500).send(err)
}
})
})
Also, if you're trying to deploy a create-react-app application, you can use this buildpack. Buildpacks are scripts that are run when your app is deployed. They are used to install dependencies for your app and configure your environment.
You can see the full code here of how I usually deploy Heroku applications.
I have worked code, which is built in /dist by webpack, for developming that is slow to wait for updating/building in dist/ folder and get result form it also. there is good "webpack-dev-server --port=4200" command but I have expressJS. How I can get updating result fast after run project. Maybe It is possable via webpack or not:
/////////////////////package.json
"scripts": {
"ng": "ng",
"dev": "concurrently nodemon ./src/index.ts \"tsc -w -p ./src\" ",
"start": "ng build && concurrently nodemon ./src/index.ts \"tsc -w -p ./src\" ",
"build": "ng build --watch",
"build:watch": "\"tsc -w -p ./src\"",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
//////////////////////index.ts
import * as express from 'express';
import { join } from 'path';
import { json, urlencoded }from 'body-parser';
var app : any = express();
app.use(express.static(join(__dirname + '/../dist')));
app.use(json());
app.use(urlencoded({
extended: true
}));
app.get('*', function(req, res, next) {
res.sendFile(join(__dirname + '/../dist/index.html'));
});
console.log('3000!! ', 3000);
app.listen(process.env.PORT || 3000);
I tried just to include ./src folder - app.use(express.static(resolve(__dirname, '../src'))); res.sendFile(resolve(__dirname, '../src/index.html')); but it is not working:
Help Please
packaje.json
dist
assets
src - app
- index.html
- index.ts