when i deploy mern on heroku deploy problem in NODE_ENV - node.js

every thing is ok but when we write the code in this format
only show api call in formate of json or send but not show the react template
i can't undersatnd
const express = require('express');
const app = express();
const port = process.env.PORT || 5000;
const NODE_ENV = process.env.NODE_ENV || "devlopment"
const path = require("path");
var cors = require('cors')
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: true }));
app.get('/', (req, res) => {
res.json({
message: "Mern Deploy secces"
})
})
app.get('/sample', (req, res) => {
res.send("Hello Express");
})
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"))
});
console.log('production modde')
}
app.listen(port, () => {
console.log('server is running on 5000')
})
this is my node js file if i write the code in this formate
only show react js not show api request
index.js
const express = require('express');
const app = express();
const port = process.env.PORT || 5000;
const NODE_ENV = process.env.NODE_ENV || "devlopment"
const path = require("path");
var cors = require('cors')
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: true }));
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"))
});
console.log('production modde')
}
app.get('/', (req, res) => {
res.json({
message: "Mern Deploy secces"
})
})
app.get('/sample', (req, res) => {
res.send("Hello Express");
})
app.listen(port, () => {
console.log('server is running on 5000')
})
This is my React js File
import Raact, { useEffect ,useState } from 'react';
import './App.css';
import axios from 'axios';
function App() {
const [show, setshow] = useState("")
useEffect(()=>{
axios.get('/',)
.then((result)=>{
setshow(result.data.message)
}).catch((err)=>{
console.log(err)
})
},[])
return (
<div className="App">
<h1>Hello world</h1>
<h1>{show}</h1>
</div>
);
}
export default App;
client package.json
{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.11.10",
"#testing-library/react": "^11.2.6",
"#testing-library/user-event": "^12.8.3",
"axios": "^0.21.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "4.0.3",
"web-vitals": "^1.1.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"proxy": "http://localhost:5000/"
}
package.json server
{
"name": "MERN-DEPLOY",
"version": "1.0.0",
"description": "",
"main": "index.js",
"engines": {
"node": "14.15.5",
"npm": "7.5.4"
},
"scripts": {
"start": "node server/index.js",
"backend": "nodemon server/index.js",
"fontend": "npm run front --prefix client",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client ",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.17.1",
"nodemon": "^2.0.7"
}
}

Related

"Cannot GET /" error message in heroku browser page

I get an error where the heroku page in browser just return this error Cannot GET / and when I am console log , it is saying 404 error but i have no idea on the error, already change the HTTPS to HTTP in server index.js .Any there change that I need to make ? Already tried other solution also not working fine it still have an error with the server, how can i fix this. Below i attach server index.js and my package.json.
server index.js
const express = require("express");
const app = express();
const http = require("https");
const { Server } = require("socket.io");
const cors = require("cors");
const server = http.createServer(app);
const user = [];
app.use(cors());
const io = new Server(server, {
cors: {
origin: "http://testing.herokuapp.com/" + (process.env.PORT || 5000),
methods: ["GET", "POST"],
},
});
io.on("connection", (socket) => {
user.push(socket.id);
socket.on("join_room", (data) =>{
socket.join(data);
})
socket.on("send_message", (data) => {
let new_data = {user_id: data.id, msg: data.text};
socket.to(data.room).emit("receive_message", new_data);
})
});
server.listen(process.env.PORT || 5000, () => {
console.log("SERVER OK");
});
package.json
{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.16.4",
"#testing-library/react": "^13.2.0",
"#testing-library/user-event": "^13.5.0",
"react": "^18.1.0",
"react-dom": "^18.1.0",
"react-scripts": "5.0.1",
"socket.io-client": "^4.5.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"autoprefixer": "^10.4.7",
"postcss": "^8.4.14",
"react-router-dom": "^6.3.0",
"tailwindcss": "^3.0.24"
}
}

Cannot connect server to client in node.js

I'm trying to connect my client to my server using socket.io to connect them. However it doén't seem to work since i don't get the socket.id in my terminal and i get this error Cannot GET / in my localhost. Please help me to fix it. Thank you so much!
client:
App.js:
import "./App.css";
import io from "socket.io-client";
const socket = io.connect("http://localhost:3000");
function App() {
return <div className="App"></div>;
}
export default App;
package.json:
{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.16.1",
"#testing-library/react": "^12.1.2",
"#testing-library/user-event": "^13.5.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "5.0.0",
"socket.io-client": "^4.4.0",
"web-vitals": "^2.1.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
server:
index.js:
const express = require("express");
const app = express();
const http = require("http");
const cors = require("cors");
const {
Server
} = require("socket.io");
app.use(cors());
const server = http.createServer(app);
const io = new Server(server, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"],
},
});
io.on("connection", (socket) => {
console.log(`User connected: ${socket.id}`);
socket.on("disconnect", () => {
console.log("User Disconnected", socket.id);
});
})
server.listen(3000, () => {
console.log("SERVER RUNNING");
});
package.json:
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon index.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"connect": "^3.7.0",
"cors": "^2.8.5",
"express": "^4.17.2",
"nodemon": "^2.0.15",
"socket.io": "^4.4.0"
}
}
For this example, the working code for the socket.io
let express = require('express');
let app = express();
let server = require('http').createServer(app);
let io = require('socket.io')(server, {
cors: {
origin: "*",
methods: ["GET", "POST"],
credentials: true
}
})

Netlify / React front end not connecting to Node.js / Express / MongoDB Atlas / Heroku backend but works in development/locally

FIX: after following some advice I ditched the setupProxy and put the full API urls into the axios request. This threw a cors error so I imported CORS & added app.use(cors()) into my index.js & when I redeployed the app ran as intended
I am trying to deploy a MERN stack practise project for the first time. I am quite a new coder.
My project works perfectly fine in development/locally. My React app running on localhost:3000 connects to the Node/Express/MongoDB Atlas API that I deployed to Heroku & can make requests successfully.
However when I open the deployed Netlify app it fails to load any data & the Heroku logs show no activity which suggests it's not connecting to the backend at all.
Here are some bits of code that may be relevant:
-----------Backend---------------
environment.js (info in <> redacted)
export const dbURI = process.env.MONGODB_URI || 'mongodb+srv://<name>:<password>#festivalist.iyq41.mongodb.net/festivalist?retryWrites=true&w=majority'
export const port = process.env.PORT || 4000
export const secret = process.env.SECRET || '<secret>'
index.js
import express from 'express'
const app = express()
import mongoose from 'mongoose'
import router from './config/router.js'
import { port, dbURI } from './config/environment.js'
const startServer = async () => {
try {
await mongoose.connect(dbURI, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true })
console.log('🚀 Database has connected successfully')
app.use(express.json())
app.use((req, _res, next) => {
console.log(`🚨 Incoming request: ${req.method} - ${req.url}`)
next()
})
app.use('/api', router)
app.listen(port, () => console.log(`🚀 Express is up and running on port ${port}`))
} catch (err) {
console.log('🆘 Something went wrong starting the app')
console.log(err)
}
}
startServer()
package.json
{
"name": "sei-project-three",
"version": "1.0.0",
"main": "index.js",
"dependencies": {
"bcrypt": "^5.0.1",
"dotenv": "^10.0.0",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"mongo": "^0.1.0",
"mongoose": "^5.12.0",
"nodemon": "^2.0.14"
},
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"seed": "node db/seeds.js",
"dev": "nodemon",
"start": "node index.js"
},
"devDependencies": {
"eslint": "^7.22.0"
},
"engines": {
"node": "16.8.0"
}
}
-------------Front end --------------
setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware')
module.exports = function (app) {
app.use(createProxyMiddleware('/api', { target: 'https://festivalist-api.herokuapp.com', "changeOrigin": true }))
}
example request
const ArtistIndex = () => {
const [artists, setArtists] = useState([])
useEffect(() => {
const getData = async () => {
const { data } = await axios.get('/api/artists')
setArtists(data)
}
console.log('artists2', artists)
getData()
}, [])
package.json
{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"axios": "^0.21.1",
"http-proxy-middleware": "^1.0.5",
"mapbox-gl": "^2.2.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-map-gl": "^5.2.5",
"react-mapbox-gl": "^5.1.1",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.3",
"sass": "^1.42.1",
"semantic-ui-css": "^2.4.1",
"semantic-ui-react": "^2.0.3"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"#typescript-eslint/eslint-plugin": "^4.25.0",
"#typescript-eslint/parser": "^4.25.0",
"babel-eslint": "^10.1.0",
"eslint": "^7.27.0",
"eslint-config-react-app": "^6.0.0",
"eslint-plugin-flowtype": "^5.7.2",
"eslint-plugin-import": "^2.23.3",
"eslint-plugin-jsx-a11y": "^6.4.1",
"eslint-plugin-react": "^7.23.2",
"eslint-plugin-react-hooks": "^4.2.0"
}
}
Some notes:
I have whitelisted all IP addresses in MongoDB Atlas 0.0.0.0/0
I'm unsure why but I have to put '/api/' on the end of the heroku api url to get the data ie: https://festivalist-api.herokuapp.com/api/festivals
I added Config Vars in Heroku but I think that stopped my app from working locally so I deleted them. Also not fully sure I understand what they do.
I have been trying to deploy this for days now so any advice would be a help or any troubleshooting tips since I am new to coding! Thanks
You have to put '/api' in at the end of heroku API because that's what you've used in your backend index.js app.use('/api', router)
The problem seems like something to do with the middle-wear setupProxy.js since you can ping the API already. One workaround is to just update your requests to use the full URI. i.e
const ArtistIndex = () => {
const [artists, setArtists] = useState([])
useEffect(() => {
const getData = async () => {
const { data } = await axios.get('https://festivalist-api.herokuapp.com/api/artists')
setArtists(data)
}
console.log('artists2', artists)
getData()
}, [])

React/Express App when deployed to Heroku only responds with index.html

I'm attempting to deploy my first react + express app. It works locally and runs both the front end and backed on port 8080. However when I deploy to heroku, the backend only responds with index.html. I've tried changing the scripts in package.json and the paths in server.js but I'm pretty stuck in terms of getting more information out of this error and what to try next. When I first deployed to heroku I received an H10 error, but then following an article recommendation I installed serve. That package resolved the H10 error, but the app doesn't respond with the json from the database. What am I missing here?
https://runtopia.herokuapp.com/
Package.json
{
"name": "runtopia",
"version": "0.1.0",
"private": true,
"dependencies": {
"#amcharts/amcharts4": "^4.9.26",
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.5.0",
"#testing-library/user-event": "^7.2.1",
"express": "^4.17.1",
"lodash": "^4.17.15",
"moment": "^2.26.0",
"nedb": "^1.8.0",
"nodemon": "^2.0.4",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.1",
"serve": "^11.3.2"
},
"scripts": {
"dev": "react-scripts start",
"start": "serve -s build",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject",
"heroku-postbuild": "npm run build"
},
"proxy": "http://localhost:8080/",
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
server.js
const express = require('express');
const path = require('path')
const app = express();
const port = process.env.PORT || 8080;
const Datastore = require('nedb');
// console.log that your server is up and running
app.listen(port, () => console.log(`Listening on port ${port}`));
app.use(express.json());
// ADDED TO WORK FOR HEROKU
app.use(express.static(path.join(__dirname,'build')));
//retrieve data from database
app.get('/chartData', (request,response) => {
db.find({},(err,data) => {
if (err){
response.end();
return
}
response.json(data)
})
})
const db = new Datastore({filename:'./database.db', autoload: true});
app.post('/fitData', (request, response) => {
const fitData = request.body
fitData.map(week =>
{
console.log("logging week",week.weekYear)
db.update({'weekYear' : week.weekYear}, week, {upsert: true, multi: true}, function (){});
})
response.json({status: "this is the backend saying, got the lastest fitbit Data!"})
})
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
app.js
import React from 'react';
import Chart2 from './Chart';
import './App.css';
import moment from 'moment';
import _ from 'lodash';
class App extends React.Component{
constructor(props){
super(props)
this.state = {
fitData:[],
chartData: [],
}
this.grab = this.grab.bind(this);
this.queryDb = this.queryDb.bind(this)
}
//populates chart with data currently in db
componentDidMount(){
this.queryDb()
}
async post(){
const options = {
method: 'POST',
headers: {
'Content-Type' : 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(this.state.fitData)
}
const response = await fetch('/fitData', options);
const data = await response.json()
console.log(data)
await this.queryDb()
}
async queryDb(){
const response = await fetch('/chartData');
const dbData = await response.json()
let sorted = dbData.sort((a, b) => (a.date > b.date) ? 1 : -1)
this.setState({chartData:sorted})
}
render(){
return (
<div className="grid-container">
<div className="Top"></div>
<div className="Title">
<p className="runtopia">RUNTOPIA.</p>
<div>
<button className="big-button" onClick= {this.grab}>Get Data</button>
</div>
</div>
<div className="Weekly">
<Chart2 key={this.state.chartData} data={this.state.chartData} />
</div>
<div className="Bottom"></div>
</div>
);
}
}
export default App;

Web app upload with nodejs server error to Heroku

I am trying to upload my app to Heroku which has frontEnd and sending mail backend both are working in my local machine. Please help anyone to solve my issue that will be of great help because this is my first and practice project to be live.
The structures and error are mentions below:
Heroku error
heroku logs --tail
client package.json
{
"name": "hephy-web",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.5.0",
"#testing-library/user-event": "^7.2.1",
"axios": "^0.19.2",
"bootstrap": "^4.4.1",
"react": "^16.13.1",
"react-bootstrap": "^1.0.0",
"react-dom": "^16.13.1",
"react-router-dom": "^5.1.2",
"react-scripts": "3.4.1"
},
"scripts": {
"start": "react-scripts start",
"heroku-postbuild": "cd client && npm install && npm run build",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
server package.json
{
"name": "hephy-back-end",
"version": "1.0.0",
"description": "Hephy BackEnd",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Uchom",
"license": "ISC",
"dependencies": {
"#sendgrid/mail": "^7.0.1",
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"express-handlebars": "^4.0.3",
"nodemailer": "^6.4.6"
}
}
server app.js
require('dotenv').config()
const path = require('path')
var express = require('express');
var router = express.Router();
var nodemailer = require('nodemailer');
var cors = require('cors');
require('dotenv').config()
var transport = {
service: 'gmail',
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASS
}
}
var transporter = nodemailer.createTransport(transport)
transporter.verify((error, success) => {
if (error) {
console.log(error);
} else {
console.log('Server is ready to take messages');
}
});
router.post('/send', (req, res, next) => {
var name = req.body.name
var email = req.body.email
var message = req.body.message
var content = `Name: ${name} \n \nE-mail: ${email} \n \nMessage: ${message} `
var mail = {
from: name,
to: 'xxxxxxxxxxx', // Change to email address that you want to receive messages on
subject: 'Hephy Inquiry Contact',
text: content
}
transporter.sendMail(mail, (err, data) => {
if (err) {
res.json({
status: 'fail'
})
} else {
res.json({
status: 'success'
})
}
})
})
const app = express()
app.use(cors())
app.use(express.json())
app.use('/', router)
app.listen(3005)
// Serve static files from the React frontend app
app.use(express.static(path.join(__dirname, 'client/build')))
it looks like you app listens to port 3005, this wont work on Heroku where you need to bind to the port provided
const PORT = process.env.PORT || 3005;

Resources