I am deploying my MERN application to Heroku. The build is successful but when I open my application the web page shows application error. I checked logs but couldn't understand much from that.
This is my first deployment of an MERN application, so please guide me. Thankyou.
These are the logs
server.js
const express = require('express');
const connectDB = require('./config/database');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 5000;
// Connect Database
connectDB();
// Init Middleware
app.use(express.json({extended: false}));
// Defining Routes
app.use('/api/users', require('./routes/users'));
app.use('/api/contacts', require('./routes/contacts'));
app.use('/api/auth', require('./routes/auth'));
// Serve static assets in production
if(process.env.NODE_ENV === 'production') {
// Set static folder
app.use(express.static('client/build'));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
})
}
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`);
});
server's package.json
{
"name": "contact-keeper",
"version": "1.0.0",
"description": "Contact Manager App",
"main": "server.js",
"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\"",
"test": "echo \"Error: no test specified\" && exit 1",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
},
"engines": {
"node": "12.18.3"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"bcrypt": "^5.0.1",
"config": "^3.3.6",
"express": "^4.17.1",
"express-validator": "^6.12.1",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.13.4"
},
"devDependencies": {
"concurrently": "^6.2.0",
"nodemon": "^2.0.12"
}
}
Related
Update #1
Unfortunately, I cannot find a screenshot from when I was working on the issue using postgrator. I ended up going with knex to try and connect to heroku instead.
However, when I run 'heroku run npm run migrate' I run into the following issue:
heroku run knex migrate:latest
Running knex migrate:latest on ⬢ stormy-hollows-73700... up,
run.6282 (Free)
Error: self signed certificate
at TLSSocket.onConnectSecure (_tls_wrap.js:1507:34)
at TLSSocket.emit (events.js:376:20)
at TLSSocket._finishInit (_tls_wrap.js:932:8)
at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:706:12)
package.json
{
"name": "express-boilerplate",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"migrate": "knex migrate:latest",
"create-migration": "knex migrate:make $1",
"migrate:test": "env NODE_ENV=test npm run migrate",
"seed": "psql -d chirp-app -f seeds/seed.posts.sql; psql -d chirp-
app -f seeds/seed.replies.sql",
"test": "mocha --require test/setup.js",
"dev": "nodemon src/server.js",
"start": "node src/server.js",
"predeploy": "npm audit",
"deploy": "git push heroku main"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"helmet": "^4.2.0",
"knex": "^0.95.4",
"morgan": "^1.10.0",
"pg": "^8.0.3",
"postgrator-cli": "^3.3.0",
"uuid": "^8.3.2",
"xss": "^1.0.8"
},
"devDependencies": {
"chai": "^4.2.0",
"mocha": "^8.2.1",
"nodemon": "^2.0.7",
"supertest": "^6.0.1"
}
}
knexfile.js
`const dotenv = require('dotenv')
dotenv.config()
module.exports = {
client: 'pg',
connection: process.env.DATABASE_URL,
ssl: { rejectUnauthorized: false }
};`
knex migration:
`exports.up = function (knex) {
return Promise.all(
[knex.schema.createTable('posts', table => {
table.string('id', 36)
table.string('title', 50)
table.string('content')
}),
knex.schema.createTable('replies', table => {
table.string('id', 36)
table.string('title', 50)
table.string('postid', 36)
})]
)
};
exports.down = function (knex) {
knex.schem.dropTable('posts')
knex.schema.dropTable('replies')
};`
Let me know if I should present this information differently, add or remove files as I am learning how to use this platform.
Thanks!
I ended up creating a knex migration and was able to validate my database on heroku.
I did have to make a "seed:live" script that runs seeds using postgres though.
ex:
"scripts": {..."seed:live": "heroku pg:psql -f seeds/seed.posts.sql; heroku pg:psql -f seeds/seed.replies.sql"...}
to validate seeding the database:
heroku pg:psql -f seeds/seed.posts.sql; heroku pg:psql -f seeds/seed.replies.sql --> Connecting to postgresql-cubed-11974 INSERT 0 3 --> Connecting to postgresql-cubed-11974 INSERT 0 2
but now it works!
I am having a simple Fastify server hosted with Heroku. But, it seems not working ! But, it seemed all right during the development! The error I get is: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch. Full error I am getting:
Here is the code I am using:
server.js:
const fastify = require("fastify")();
const path = require("path");
fastify.register(require("fastify-static"), {
root: path.join(__dirname, "/"),
});
fastify.get("/", function (req, reply) {
reply.sendFile("index.html");
});
fastify.listen(process.env.PORT || 5000, (err) => {
if (err) throw err;
console.log(`server listening on ${fastify.server.address().port}`);
});
package.json:
{
"name": "test1",
"version": "1.0.0",
"description": "",
"main": "server.js",
"engines": {
"node": "15.11.x"
},
"scripts": {
"start": "node server.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"fastify": "^3.14.0",
"fastify-static": "^4.0.1"
}
}
Sometimes, the site even doesn't load!
Any help is greatly appreciated !
Thanks !
That's an issue with the library. For other libraries (express, django, etc..) specifying the address is not necessary.
See https://github.com/fastify/fastify/issues/709
Change:
.listen(process.env.PORT)
to:
.listen(process.env.PORT, '0.0.0.0')
When I use both nodemon as local server and Heroku for production the following works for me:
await fastify.listen(process.env.PORT, process.env.HOST || '0.0.0.0');
and in package.json
"dev": "PORT=${PORT:=3000} HOST=${HOST:=localhost} nodemon"
I've written a pretty simple app in Preact. No back end server, just front-end calling a web API and displaying the results.
I set it up on Heroku and it reports that it deployed successfully, but trying to access the app fails right out the gate:
2020-09-14T02:10:11.845503+00:00 heroku[web.1]: Starting process with command `npm start`
2020-09-14T02:10:14.403769+00:00 app[web.1]: npm ERR! missing script: start
How should I [define a start script to] make this work?
In development I run yarn dev like the Preact docs suggest. My guess is that's just a dev server though.
FWIW, Here's my package.json
{
"private": true,
"name": "clips-preact",
"version": "0.0.0",
"license": "MIT",
"scripts": {
"build": "preact build",
"serve": "sirv build --port 8080 --cors --single",
"dev": "preact watch",
"lint": "eslint src"
},
"eslintConfig": {
"extends": "eslint-config-synacor"
},
"eslintIgnore": [
"build/*"
],
"devDependencies": {
"eslint": "^6.0.1",
"eslint-config-synacor": "^3.0.4",
"preact-cli": "^3.0.0",
"sirv-cli": "^1.0.3"
},
"dependencies": {
"axios": "^0.20.0",
"preact": "^10.1.0",
"preact-render-to-string": "^5.1.2",
"recoil": "^0.0.10"
}
}
I'm late, but to anyone who comes across this, you shouldn't be running a separate server at all.
Preact CLI builds to static output. Just point your webserver (nginx, apache) at the directory and let it handle serving the files.
Give this a try:
{
"private": true,
"name": "clips-preact",
"version": "0.0.0",
"license": "MIT",
"scripts": {
"build": "preact build",
"serve": "sirv build --port 8080 --cors --single",
"dev": "preact watch",
"lint": "eslint src",
// Your file name ↓ make sure to remove this comment before you go.
"start": "node index.js"
}
You have to add "start" inside the "scripts" area, then as you running your script type "node your_file_name" this will make "npm start" command run "node your_file_name" command.
I have created app using reactjs, nodejs(restify) and postgresql, I build successfully on Heroku but when i open my app I am getting error {"code":"ResourceNotFound","message":"/ does not exist"} I am try to add serverStaticFiles() but it gives me AssertionError [ERR_ASSERTION]: directory (string) is required so I removed it now Now help me to find what i did wrong here...
Server.js
var restify=require('restify')
const { logIn,userCreation, demotable } = require('./routes/Function');
const corsMiddleware = require('restify-cors-middleware2');
const { data } = require('jquery');
const PORT=process.env.PORT || 8080;
var path=require('path')
var server=restify.createServer() //server created
server.use(
function crossOrigin(req,res,next){
res.header("Access-Control-Allow-Origin", "*");
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
res.setHeader('Access-Control-Allow-Credentials', true); // If needed
res.header("Access-Control-Allow-Origin", "*");
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
return next();
}
);
const cors = corsMiddleware({
preflightMaxAge: 5, //Optional
origins: ['*'],
allowHeaders: ['*'],
exposeHeaders: ['*']
})
server.pre(cors.preflight)
server.use(cors.actual)
//setting
// if (process.env.NODE_ENV === "production") {
// //server static content
// //npm run build
// server.use(restify.static(path.join(__dirname, "client/build")));
// }
console.log(__dirname);
console.log(path.join(__dirname, "client/build"));
//get data from login form
server.post('/note', userCreation);
server.use(restify.plugins.bodyParser());
server.get('/login',logIn)
server.get('/employees',demotable)
if(process.env.NODE_ENV==='production')
{
server.get('/client/build/*', restify.plugins.serveStatic({
directory: __dirname,
default: 'index.html'
}));
// server.use(restify.serveStatic('client/build'))
// server.get('*',(req,res)=>{
// res.sendFile(path.join(__dirname,'client','build','index.html'))
// })
}
// server.get("*", (req, res) => {
// res.sendFile(path.join(__dirname, "client/build/index.html"));
// });
server.listen(PORT, function(){
console.log("server started...")
})
package.json
{
"name": "backend",
"version": "1.0.0",
"engines": {
"npm": "6.x",
"node": "12.18.2"
},
"description": "",
"main": "index.js",
"start": "node Server.js",
"heroku-postbuild": "cd client && npm install && npm run build",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node Server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"dotenv": "^8.2.0",
"jquery": "^3.5.1",
"pg": "^8.3.0",
"pg-hstore": "^2.3.3",
"restify": "^8.5.1",
"restify-cors-middleware2": "^2.1.0",
"sequelize": "^6.3.3"
},
"devDependencies": {
"nodemon": "^2.0.4"
}
}
You should put the "start": "node server.js" inside the scripts section like
"scripts": {
"start": "node server.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
My team and I created a MERN stack application (M for MySQL) that is planning on hosting our client on gh-pages and our server on heroku. So far we have been unable to deploy because we keep getting errors about our use of the npm package concurrently. Although we can access our heroku url and our gh-pages url, we are unable to connect the two
We have already tried adding a proxy to our package.json within our client folder and have added a .env.development Host name (heroku url)
Root Directory
- client
- package.json
- package-lock.json
- config
- config.json
- passport.json
- controllers
- models
- routes
- .env
- .env.development
- .gitignore
- package-lock.json
- package.json
- server.js
Server package.json
{
"name": "traveler",
"version": "1.0.0",
"homepage": "http://dchicchon.github.io/Traveler",
"description": "A social media platform for people who love traveling and those who want to explore.",
"main": "server.js",
"scripts": {
"start": "if-env NODE_ENV=production && npm run start:prod || npm run start:dev",
"start:prod": "node server.js",
"start:dev": "concurrently \"nodemon --ignore 'client/*'\" \"npm run client\"",
"client": "cd client && npm run start",
"seed": "node scripts/seedDB.js",
"install": "cd client && npm install",
"build": "cd client && npm run build",
"heroku-postbuild": "npm run build"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"aws-sdk": "^2.511.0",
"bcryptjs": "^2.4.3",
"concurrently": "^4.1.1",
"dotenv": "^8.0.0",
"express": "^4.17.1",
"express-session": "^1.16.2",
"gh-pages": "^2.0.1",
"multer": "^1.4.2",
"multer-s3": "^2.9.0",
"mysql2": "^1.6.5",
"passport": "^0.4.0",
"passport-local": "^1.0.0",
"sequelize": "^5.13.1"
},
"devDependencies": {},
"repository": {
"type": "git",
"url": "git+https://github.com/dchicchon/Traveler.git"
},
"bugs": {
"url": "https://github.com/dchicchon/Traveler/issues"
}
}
Client package.json
{
"name": "traveler",
"version": "0.1.0",
"proxy": "https://travelersite.herokuapp.com/",
"private": true,
"dependencies": {
"axios": "^0.19.0",
"google-map-react": "^1.1.4",
"lodash": "^4.17.15",
"materialize-css": "^1.0.0",
"react": "^16.9.0",
"react-dom": "^16.9.0",
"react-router-dom": "^5.0.1",
"react-scripts": "3.1.0",
"styled-components": "^4.3.2"
},
"scripts": {
"predeploy": "npm run build",
"deploy": "gh-pages -d build",
"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": {
"gh-pages": "^2.1.1"
}
}
After entering the command heroku create and git push heroku master we would expect that our server will be pushed to heroku and our client will be deployed to gh-pages.
Does removing heroku-postbuild script from your backend package.json work?