Web app upload with nodejs server error to Heroku - node.js

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;

Related

Why i'm not able to GET while deploying in heroku? but locally it can postable

I'm new for mern development and my app was not able to fetch post while deployment in heroku.
I have no idea about this.
i was attached procfile web:node app.js also
after that also i'm not able to fetch post
it return 503 error
{
"name": "site",
"version": "1.0.0",
"engines": {
"node": "16.17.0",
"npm": "8.15.0"
},
"description": "site for buying AR and VR product",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node app.js",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
},
"author": "Farooq",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"cookie-parser": "^1.4.6",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"jsonwebtoken": "^8.5.1",
"mongoose": "^6.7.0",
"pg": "^8.8.0"
},
"devDependencies": {
"nodemon": "^2.0.20"
}
}
my app.js file
const express = require('express');
const dotenv = require('dotenv');
const cookieParser = require('cookie-parser')
const port = process.env.PORT||5000;
const app = express();
const path = require('path')
// const path = require('path')
dotenv.config({path:"./config.env"})
require('./db/conn')
const userSchema = require('./model/userSchema');
app.use(cookieParser())
app.use(express.json())
app.use(require('./routes/auth'))
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(port, ()=>{
console.log(`site is listening at port ${port}`)
})
client folder package.js
{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.16.5",
"#testing-library/react": "^13.4.0",
"#testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.4.2",
"react-scripts": "^5.0.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.12",
"postcss": "^8.4.18",
"tailwindcss": "^3.1.8"
}
}
I need to fetch the data by post method while deployment

My react frontend not establishing connection with my node backend

I am trying to get my react frontend to establish connection with my node backend. The node backend works when I am using PostMan. I have gone through most of the options suggested on this plateform but none is helping.
This is the Fetch request in react
import axios from 'axios'
// Sending Request to register User
let URL = "/user/"
const register = async (userData) => {
let response = await axios.post(URL + 'register', userData)
if (response.data) {
localStorage.setItem('user', JSON.stringify(response.data))
}
return register.data
}
This is my package.json file for the react:
{
"name": "frontend",
"version": "0.1.0",
"private": true,
"options": {
"allowedHosts": [
"localhost",
".localhost"
],
"proxy":"http://localhost:8000"
},
"dependencies": {
"#reduxjs/toolkit": "^1.8.6",
"#testing-library/jest-dom": "^5.16.5",
"#testing-library/react": "^13.4.0",
"#testing-library/user-event": "^14.4.3",
"axios": "^1.1.2",
"bootstrap": "^5.2.2",
"react": "^18.2.0",
"react-bootstrap": "^2.5.0",
"react-dom": "^18.2.0",
"react-icons": "^4.4.0",
"react-redux": "^8.0.4",
"react-router-dom": "^6.4.2",
"react-scripts": "5.0.1",
"react-toastify": "^9.0.8",
"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"
]
}
}
This is my Node index.js file to handle the post request
require('dotenv').config()
const express = require('express')
const bodyParser = require('body-parser')
const { connectToDb } = require('./database/db');
const cors = require('cors')
const port = process.env.PORT || 5000
connectToDb();
const app = express()
app.use(express.json())
app.use(bodyParser.urlencoded({extended:true}))
app.use(cors())
app.use('/user', require('./routes/userRoutes'))
app.listen(port, () => {
console.log(`Server is running on ${port}`)
})
What should am I not doing right?

"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()
}, [])

Resources