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"
Related
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"
}
}
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 have a graphql project using the prism but when executing the command npx prisma deploy -e ../config/dev.env I get the following error:
post-deploy:
[
"[WARNING] in D:\\Projetos\\graphql3\\graphql-prisma\\prisma\\prisma.yml: A valid environment variable to satisfy the declaration 'env:PRISMA_ENDPOINT' could not be found."
]
ListrError: Something went wrong
at D:\Projetos\graphql3\graphql-prisma\node_modules\listr\index.js:102:18
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at async executeCodegen (D:\Projetos\graphql3\graphql-prisma\node_modules\#graphql-codegen\cli\index.cjs.js:812:5)
at async Object.generate (D:\Projetos\graphql3\graphql-prisma\node_modules\#graphql-codegen\cli\index.cjs.js:1102:25)
at async Object.handler (D:\Projetos\graphql3\graphql-prisma\node_modules\#graphql-cli\codegen\index.cjs.js:23:13) {
errors: [
Error: No cluster set. Please set the "cluster" property in your prisma.yml
at PrismaLoader.load (D:\Projetos\graphql3\graphql-prisma\node_modules\#graphql-tools\prisma-loader\index.cjs.js:1296:19)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at async loadFile (D:\Projetos\graphql3\graphql-prisma\node_modules\#graphql-tools\load\index.cjs.js:48:24)
at async D:\Projetos\graphql3\graphql-prisma\node_modules\#graphql-tools\load\index.cjs.js:425:24 {
source: './src/generated/prisma.graphql',
context: [Object: null prototype] {}
}
],
context: [Object: null prototype] {}
}
The project's folder architecture is in this format
my prisma.yml
endpoint: ${env:PRISMA_ENDPOINT}
datamodel: datamodel.graphql
secret: thisisasecret
hooks:
post-deploy:
- graphql codegen --project database # instead of graphql get-schema
# - prisma generate**strong text**
config\dev.env has content
PRISMA_ENDPOINT=http://localhost:4466
package.json
{
"name": "graphql-basics",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "nodemon src/index.js --ext js,graphql --exec babel-node",
"test": "echo \"Error: no test specified\" && exit 1",
"get-schema": "graphql codegen --project database"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-cli": "^6.26.0",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-preset-env": "^1.7.0",
"bcryptjs": "^2.4.3",
"env-cmd": "^10.1.0",
"graphql-cli": "^4.0.0",
"graphql-yoga": "^1.14.10",
"jsonwebtoken": "^8.5.1",
"prisma-binding": "^2.3.16"
},
"devDependencies": {
"#graphql-cli/codegen": "^1.17.8",
"#graphql-codegen/schema-ast": "^1.17.8",
"nodemon": "^1.17.5"
}
}
I didn't find anything related and even trying to put the .env in the root where the prisma.yml file is, with the default name .env doesn't work
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"
},
I'm trying to Host my bot "chompbot" in Heroku.
But when i change Procfile from web to worker, does not change anything.
I've tried
Here is my package.json
"name": "chompbot",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"discord.js": "^11.5.1",
"mysql": "^2.17.1"
}
}
And here is my Procfile
worker: index.js
When i commit and push, anything happens on "Web", and do not appears "Worker" option
( Ps.: The MySql database is fully working on cloud, so, can't be the dependencies )
Can someone help me to change from Web to Worker?
http://prntscr.com/pb21qs
Your worker should be the script that starts you server, index.js is only the file name. What you want to do is to use your npm start script instead of index.js