I am hosting my very simple nodejs server in Heroku. But, when I try it, it returns this error:
Application error
An error occurred in the application and your page could not be served. If you are the application
owner, check your logs for details. You can do this from the Heroku CLI with the command`
Here's the server.js:
const express = require("express");
const cors = require("cors");
const PORT = process.env.PORT || 80;
const server = express();
server.use(cors());
server.get("/", (req, res) => {
const INDEX = "/index.html";
res.sendFile(INDEX, { root: __dirname });
});
server.get("/test", (req, res) => {
res.send("test Page");
});
server.listen(PORT, () => console.log(`listening on port ${PORT}`));
package.json:
{
"name": "express-heroku",
"version": "1.0.0",
"description": "",
"main": "server.js",
"engines": {
"node": "15.11.x"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"mongoose": "^5.11.19"
},
"devDependencies": {
"nodemon": "^2.0.7"
}
}
Don't know what the reason is, but, when I try this in the localhost it works perfectly!
The full error on Heroku CLI:
Any help is greatly appreciated !
Create a ProcFile:
Inside the ProcFile add web: node index.js
Doing this, you are telling heroku to run your server, with node.
Related
I've been working to deploy my app to Heroku but keep running into an H10 error. The app works locally but no luck deploying to Heroku.
Here is the index.js:
import express from 'express'
import 'dotenv/config'
import router from './routes/index.js'
import morgan from 'morgan'
const app = express()
const port = process.env.PORT || 5000
app.use('/public', express.static('public'))
app.use(express.urlencoded({ extended: false }))
app.use(express.json())
app.use(morgan('dev'))
app.use('/', router)
app.listen(process.env.PORT || port)
Here is my Procfile:
web: node index.js
Here is the package.json:
{
"name": "node-sso-example-app",
"version": "1.0.0",
"description": "Example Node.js SSO App using WorkOS",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node index.js"
},
"author": "WorkOS",
"dependencies": {
"express": "^4.18.1",
"ejs": "^3.1.8",
"router": "^1.3.7",
"dotenv": "^16.0.1",
"#workos-inc/node": "^2.11.0",
"morgan": "^1.10.0",
"cookie-parser": "^1.4.6",
"express-session": "^1.17.2",
"http-errors": "~1.6.3"
},
"devDependencies": {
"nodemon": "^2.0.19"
},
"engines": {
"node": "^16.17.0"
}
}
I'm stuck at this point and have read through what feels like every Stackoverflow question on this same error with no luck.
i'm new to nodejs and heroku but i was facing the same problem H10.
It is probably related to ports.
Try to remove this line completely
const port = process.env.PORT || 5000
and add this for index.js (I believe you can use any port and Heroku can manually allocate a different port
//start server
app.listen(process.env.PORT || 3000, function(){
console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
});
Or keep const port, but use this instead:
app.listen(port, () => {
console.log(`server started on port ${port}`);
})
I created one demo app with ReactJS, NodeJS, MongoDb and Express. Trying to deploy on heroku. It works fine, if i dont use mongo, but as soon as i introduced mongo db. I am getting error cannot GET /.
I am using mongodb atlas. Do I need heroku addon to use database?
server.js
// Import dependencies
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');
const MongoClient = require("mongodb").MongoClient;
const ObjectId = require("mongodb").ObjectID;
const mongodb = require('mongodb');
const fs = require('fs');
const moment = require("moment");
require('dotenv').config();
const CONNECTION_URL = process.env.MONGODB_URI || "mongodb+srv://<username>:<password>#cluster0.xzzno.mongodb.net/<dbname>?retryWrites=true&w=majority";
const DATABASE_NAME = "DBNAME";
const port = process.env.PORT || 5000;
const app = express();
// Set our backend port to be either an environment variable or port 5000
// This application level middleware prints incoming requests to the servers console, useful to see incoming requests
app.use((req, res, next) => {
console.log(`Request_Endpoint: ${req.method} ${req.url}`);
next();
});
// Configure the bodyParser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
// Configure the CORs middleware
app.use(cors());
app.get("/test/", (request, response) => {
response.send({"name":"Hello Test!!!"});
});
var database, userSignUp;
app.listen(port, () => {
MongoClient.connect(CONNECTION_URL, { useNewUrlParser: true }, (error, client) => {
if(error) {
throw error;
}
database = client.db(DATABASE_NAME);
userSignUp = database.collection("UserData");
console.log("Connected to `" + DATABASE_NAME + "`!");
});
})
package.json
{
"name": "testproject",
"version": "1.0.0",
"description": "Learning Deployment",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"client": "cd client && npm start",
"server": "nodemon server.js",
"dev": "concurrently --kill-others-on-fail \"npm run client\" \"npm run server\"",
"client:build": "cd client && npm run build"
},
"repository": {
"type": "git",
"url": "git+https://github.com/Username/TestProject.git"
},
"author": "Ankita Jaiswal",
"license": "ISC",
"bugs": {
"url": "https://github.com/Username/TestProject/issues"
},
"homepage": "https://github.com/Username/TestProject#readme",
"dependencies": {
"body-parser": "^1.19.0",
"concurrently": "^5.3.0",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"nodemon": "^2.0.7",
"moment": "^2.29.1",
"mongodb": "^3.6.3",
"mongoose": "^5.11.8"
}
}
procfile
web: npm run dev
have tried web: npm start as well.
Just from my limited experience, I've had the same issue and it turned out I forgot to configure my environment variables on Heroku, so my MONGO_URI was undefined. If not that, you can use the Heroku CLI and run heroku logs --tail from the root of your project and might be able to see more about what's going on.
const CONNECTION_URL = process.env.MONGODB_URI || "mongodb+srv://<username>:<password>#cluster0.xzzno.mongodb.net/<dbname>?retryWrites=true&w=majority";
The upper code is incorrect. You have to change < username > and < password > (both include < >) by your usename and your password! Example:
const CONNECTION_URL = process.env.MONGODB_URI || "mongodb+srv://kanechan25:kane02052409#cluster0.xzzno.mongodb.net/<dbname>?retryWrites=true&w=majority";
I don't understand why is my code logging messages two times when I'm just creating only one server and loading it once in the browser.
INPUT -
const express = require('express');
const app = express();
app.use((req, res, next) => {
console.log('Hello middleware')
next(); // Allows the request to continue to the next middleware in line
});
app.use((req, res, next) => {
console.log('Hello middleware v2')
res.send('<h1>Hello Express!</h1>');
});
app.listen(3000);
OUTPUT -
[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
Hello middleware
Hello middleware v2
Hello middleware
Hello middleware v2
package.json -
{
"name": "nodeproject1",
"version": "1.0.0",
"description": "node tutorial",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon app.js"
},
"author": "Arkapratim Sarkar",
"license": "ISC",
"devDependencies": {
"nodemon": "^2.0.6"
},
"dependencies": {
"express": "^4.17.1"
}
}
If you perform the request through your browser not only will a request be sent for the corresponding request-path (e.g./) but also for /favicon.ico (details are explained here).
Since two requests are made, you see each of your middleware's log message twice.
My Node.js script is unable to be deployed to Heroku and the error comes in the console saying that I'm missing my start script even though I have it.
Package.JSON
{
"name": "kash",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node app.js"
},
"author": "",
"license": "ISC"
}
App.js
var express = require("express");
var request = require("request");
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.listen((process.env.PORT || 5000));
// Server index page
app.get("/", function (req, res) {
res.send("Deployed!");
});
// Facebook Webhook
// Used for verification
app.get("/webhook", function (req, res) {
if (req.query["hub.verify_token"] === process.env.VERIFICATION.TOKEN) {
console.log("Verified webhook");
res.status(200).send(req.query["hub.challenge"]);
} else {
console.error("Verification failed. The tokens do not match.");
res.sendStatus(403);
}
});
Console Log screenshots:
Screenshot 1
Screenshot 2
I am trying out to host a node.js project on Openshift, here is my package.json:
"scripts": {
"start": "node index.js"
},
"main": "index.js",
"dependencies": {
"express": "^4.13.3",
"formidable": "^1.0.17"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node index.js"
},
...
and here is my index.js
var express = require('express');
var app = express();
var http = require('http');
app.set('port', process.env.OPENSHIFT_NODEJS_PORT || process.env.PORT || 8080);
app.set('ip', process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1");
app.get('/', function(req,res){
res.send("Hello World");
});
http.createServer(app).listen(app.get('port') ,app.get('ip'), function () {
console.log("✔ Express server listening at %s:%d ", app.get('ip'),app.get('port'));
server();
});
What am I missing and how can I successfully see the expected "Hello World" message? Thanks!
I don't see anything wrong with your could, and I bet “Service Temporarily Unavailable” means exactly that, in this case. Simply try again later after the scheduled maintenance.
Also, check the scheduled maintenances at http://status.openshift.com/ or #openshift_ops