React App on Heroku getting Invalid Host Header - node.js

Deployed my React App onto Heroku and opened my app to get an Invalid Host Header.
Anyone have any ideas what else might be causing this? I keep looking back at past projects to see if I have anything setup differently, but so far can't figure it out.
I tried every solution I could find online, and the only one that got the page to load was to remove my "proxy": "http://localhost:8080" from my package.json but the app can't use the back-end.
if (process.env.NODE_ENV !== 'production') {
console.log('loading dev environments');
require('dotenv').config();
}
require('dotenv').config();
if (process.env.NODE_ENV === 'production') {
const path = require('path');
console.log('YOU ARE IN THE PRODUCTION ENV');
app.use('/static', express.static(path.join(__dirname, '../build/static')));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '../build/'));
});
}
Figured it has to do with not switching to a production configuration but I have my files setup the same way as past projects and have the code for my node server to change for production too.

Related

express app is not sending index.html file to client

So my express app has a small Node server setup so it can serve up the index.html file when the home route '/' is hit. This is a requirement of using the App Services from Azure, there has to be this server.js file to tell the server how to serve up the client, and i had a previous implementation of this working, however i wanted to change my file structure. previously i had, the client React app in a folder client and the server.js in a folder server along with all of the conrtollers and routes. i've since moved the server API to its own application as there are other apps that depend on it. and i moved the client up one directory into the main directory. Everything was working fine till the other day when all of the sudden when you hit the home route / it will not serve up the index.html file. if you hit any other route it works, if you even hit a button linking back to the homepage, it works, but it wont serve up the app from the / and i cannot for the life of me figure out why, on my development server there are no errors in the console. and im most definitely targeting the correct directory and place for the index. but its like the server isnt reading the route to serve up.
if (process.env.NODE_ENV === 'production') {
console.log('running');
app.use(express.static(path.resolve(path.join(__dirname, 'build'))));
// no matter what route is hit, send the index.html file
app.get('*', (req, res) => {
res.sendFile(path.resolve(path.join(__dirname, 'build', 'index.html')));
});
} else {
app.get('/', (req, res) => {
res.send('API is running...');
});
}
So here im saying if the NODE_ENV is in production make the build folder static, and then whatever route is hit. (Note: i also tried this app.get with other route formats such as /* or / all have the same issues. however in my previous iteration when the client and server where deployed in the same location, /* is what i used.) The .env varialbes are setup correctly, as when the server is ran, itll console log running.. but even if i put a console log inside of the app.get() its like its never hit unless i access the route from something else first.
for example, if i place a console log inside of app.get that states hit whenever the route is hit, hitting / directly does nothing, but if i go to /login itll serve up the correct html on the client and console log hit in the terminal...
If you are having server files inside the client react app, then we are basically accessing file which are not inside our server file. So, we can serve static files using the following code:
const express = require("express");
const app = express(); // create express app
const path = require('path');
app.use(express.static(path.join(__dirname, "..", "build")));
app.use(express.static("build"));
app.listen(5000, () => {
console.log("server started on port 5000");
});
Now in your packages.json of the client react app change the name of start tag under scripts tag to start-client. Then add this following tag to the scripts tag:
"start":"npm run build && (cd server && npm start)",
Basically, this will build the react app and start the server.
It should look like this :
Also in the packages.json of your server add the following tag under script tag
"start":"node server.js"
So when you run the following command npm start it should look like this :

How to deploy NextJS application to Linux Server (CentOS 7) - VPS

I've got a question regarding building applications. I'm using simple VPS with node.js support. Now I do not know how to build my next.js application to production.
I want to deploy my application as static files.
I thought that I should use next build && next export then copy out dir to the server but during this process, I faced some issues - when I change route - everything is okay, but if I refresh the page - the page is not found because the server is looking for this file in directories. So how can I deploy my nextjs application in production mode with VPS server and static files?
I tried one thing which is not working fine probably or I did something wrong.
I added nodejs express server with
const express = require('express');
const next = require('next');
const dev = process.env.NODE_ENV !== 'production';
const app = next({dev});
const router = express.Router();
const handle = app.getRequestHandler();
app.prepare()
.then(() => {
const server = express();
server.get('*', (req, res) => {
return handle(req, res);
});
server.listen(3000, (err) => {
if (err) throw err;
console.log('> Ready on http://localhost:3000');
});
});
and start server with forever library NODE_ENV=production node server.js and it's working fine, but seems this is working in a wrong way - seems it's normal server like in dev mode - so it shouldn't be like that. (I see thunder icon on the right-bottom corner and I see all files which are same as in dev mode).
I want to deploy everything as static files.
Thank you for your help!
After you build and export you need to serve those files somehow. The reason the Express server works is because you are starting a HTTP server to serve the files.
So you need to serve those files either by using a static hosting provider (i.e. Vercel or Amazon S3). Otherwise you should start a server on your linux machine using something like serve to serve it at a port, similar to your Express server serving it as localhost:3000 which is then exposed on your VPS.

A deployed Heroku app works online only on the PC I deployed it from

I finished my MERN stack app and deployed it to Heroku. Opened it on Heroku and it worked. Funny thing is, it doesn't work on any other machine other than the one I deployed it from.
When opened on any other machine, it just goes to blank white screen with the following error in console:
redux.js:575 Uncaught TypeError: Cannot read property 'apply' of undefined
at redux.js:575
at u (redux.js:79)
at Module.102 (store.js:9)
at f ((index):1)
at Object.57 (spinner.gif:1)
at f ((index):1)
at a ((index):1)
at Array.e [as push] ((index):1)
at main.4febefcb.chunk.js:1
I am trying to figure out what are the possible causes of this behavior.
I've already tried creating a new Heroku app and re-deploying it, restarting dynos and checking my server.js config for ports.
//static assets for production
if (process.env.NODE_ENV === "production") {
//set a static folder
app.use(express.static("client/build"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
});
}
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server is being ran on port ${PORT}`));
Where should I be looking to locate the issue?
After plenty of debugging, I have isolated the issue to Redux dev tools. The app worked with any browser that had Redux dev tools installed.
I figured out it had something to do with store.js file and examined my createStore:
const store = createStore(
rootReducer,
initialState,
compose(
applyMiddleware(...middleware),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
)
);
After removing the following line from compose
window.REDUX_DEVTOOLS_EXTENSION &&
window.REDUX_DEVTOOLS_EXTENSION()
I pushed it to Heroku and the problem was solved.

Deploying issue with react,nodejs,express on production

This is my first project using nodejs and react, I have been working a aplication by following this this tutorial.Its working fine localhost
but not working on prodution mode.I have created a build and its generated a directory called "dist". I have moved everthing to live server from "Dist" folder.
But the node route not working , its says 404 error.How to deploy nodejs with react on production?
Can please help me get rid of it?
Thanks
Your backend server will not know how to handle the routes on your client or know the location of your "client" folder, if you have a dist folder you would need to do something similar to this:
if (process.env.NODE_ENV === 'production') {
app.use(express.static('dist'));
const path = require('path');
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'dist', 'index.html'));
});
}
Hope this helps.

Why is my server causing a syntax error when deployed to Heroku but runs with no errors locally (using Create React App, Node/Express)?

Edit to add picture of exact error, and to provide more info
When I click on main.35...js in the error message in the console, it shows me the source code to my index.html, all of it with the red underline, but I don't see the erroneous syntax there:
<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no"><meta name="theme-color" content="#000000"><link rel="manifest" href="/manifest.json"><link rel="shortcut icon" href="/favicon.ico"><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"><title>BoGoodSki.com</title><link href="/static/css/main.4d5a52c0.css" rel="stylesheet"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div><script type="text/javascript" src="/static/js/main.35eb4822.js"></script></body></html>
Also, in development, there is no error or warning in VSCode regarding the index.html file. I'm confused for sure.
Thanks for the help so far!
End edit
I have an app deployed to Heroku that has been working well.
Today I made some changes to the Express server to handle a simple API post request to a MongoDB instance on mLab. I had to set up CORS policy as middleware but, otherwise, I didn't make any substantial changes to the server code.
My deployment flow has been to run 'npm run build' on the Create React App client, and then use the Heroku CLI to git push from my server folder. This process has worked well. Until today.
Now, when I deploy to Heroku, it says that it publishes successfully, but the app is blank in the browser and the console says that there is a syntax error of < in the build JS file. I can't currently reproduce the error because I rolled back to a working deployment in Heroku.
Here is my server code. Can you identify what may be causing the issue? My JS build files sit in client/build/static, just like Express expects them to, so I don't know what's up.
Appreciate the help.
index.js:
const express = require('express');
const mongoose = require('mongoose');
const keys = require('./config/config');
require('./models/FormData');
var bodyParser = require('body-parser');
mongoose.connect(keys.mongoURI);
const app = express();
const FormMessage = mongoose.model('formMessages')
app.use(function (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.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.post("/submitMessage", (req, res) => {
var newMessage = new FormMessage(req.body);
newMessage.save()
.then(item => {
res.status(200).send();
})
.catch(err => {
res.status(400).send();
});
});
if (process.env.NODE_ENV === 'production') {
app.use(express.static('client/build'));
const path = require('path');
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'))
});
}
const PORT = process.env.PORT || 5000;
app.listen(PORT);
Fixed!!
Okay. Here are the steps that I took. I'm not sure which, individually, resolved the problem. But, altogether, they worked.
First, I deleted the existing main.35...js file in my source code direetory. Actually, I deleted the entire build/static folder. And then ran "npm run build" in the client directory to rebuild the React app.
I changed the node engine in my package.json from 8.1.1 to the version I am running locally, 9.2.1.
In my index.js, I removed the conditional regarding the production environment variable because, it occurred to me that it didn't make sense to serve it up differently locally than I would in production; I think that conditional was a remnant from something I had been working on earlier in the project.
Those steps taken together have done the trick. I appreciate all who have viewed this question and given it any thought. Thanks!

Resources