Firebase CloudScheduler GCLOUD_PROJECT error - node.js

This is my function with the configuration at the top, and the function at the bottom
const functions = require('firebase-functions')
const Stripe = require('stripe')
const axios = require('axios')
const admin = require('firebase-admin')
const serviceAccount = require('./serviceAccountKey.json')
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: 'https://c6dcc.firebaseio.com'
})
exports.detectConnect = functions.pubsub
.topic('detectConnect')
.onPublish(async message => {
console.log('THIS THING RAN')
return null
})
These are my dependencies
"dependencies": {
"#google-cloud/storage": "^2.0.0",
"axios": "^0.19.0",
"child-process-promise": "^2.2.1",
"firebase-admin": "~7.0.0",
"firebase-functions": "^2.2.0",
"mkdirp": "^0.5.1",
"mkdirp-promise": "^5.0.1",
"node-fetch": "^2.6.0",
"request": "^2.88.0",
"stripe": "^7.1.0"
},
But firebase throws an error
Error: process.env.GCLOUD_PROJECT is not set.
at TopicBuilder (/srv/functions/node_modules/firebase-functions/lib/providers/pubsub.js:43:19)
at cloudFunctionNewSignature (/srv/functions/node_modules/firebase-functions/lib/cloud-functions.js:102:13)
at cloudFunction (/srv/functions/node_modules/firebase-functions/lib/cloud-functions.js:151:20)
at Promise.resolve.then (/srv/node_modules/#google-cloud/functions-framework/build/src/invoker.js:330:28)
at process._tickCallback (internal/process/next_tick.js:68:7)
The error is also present when using schedule-functions

If you're running Node 10, please make sure you're on the latest version of firebase-tools and make sure you're deploying using the Firebase CLI. As of Node 10, the GCLOUD_PROJECT environment variable is no longer available by default.
If you're still running into problems, try changing your Node engine in package.json to "8" and see if you have more success.

Related

not able to deploy firebase function in nodejs

Hi I am unable to deploy functions using firebase, I am getting the below error.
On trying to look at the logs could not find anything concrete.
If someone can please help me to resolve this issue.
Below are the necessary details.
error displayed :
Function failed on loading user code. This is likely due to a bug in the user code. Error message: Error: please examine your function logs to see the error cause: https://cloud.google.com/functions/docs/monitoring/logging#viewing_logs. Additional troubleshooting documentation can be found at https://cloud.google.com/functions/docs/troubleshooting#logging. Please visit https://cloud.google.com/functions/docs/troubleshooting for in-depth troubleshooting documentation.
Functions deploy had errors with the following functions:
app(us-central1)
i functions: cleaning up build files...
Error: There was an error deploying functions
On running function:log got the below :
2022-09-15T08:09:56.119842Z ? app: at require (node:internal/modules/cjs/helpers:102:18)
2022-09-15T08:09:56.119851Z ? app: at Object.<anonymous> (/workspace/index.js:10:32)
2022-09-15T08:09:56.119860Z ? app: at Module._compile (node:internal/modules/cjs/loader:1105:14)
2022-09-15T08:09:56.119869Z ? app: at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
2022-09-15T08:09:56.119877Z ? app: at Module.load (node:internal/modules/cjs/loader:981:32)
2022-09-15T08:09:56.119893Z ? app: at Function.Module._load (node:internal/modules/cjs/loader:822:12)
2022-09-15T08:09:56.119902Z ? app: at Module.require (node:internal/modules/cjs/loader:1005:19)
2022-09-15T08:09:56.120112Z ? app: Could not load the function, shutting down.
2022-09-15T08:09:56.385832481Z E app: Function cannot be initialized. Error: function terminated. Recommended action: inspect logs for termination reason. Additional troubleshooting documentation can be found at https://cloud.google.com/functions/docs/troubleshooting#logging
2022-09-15T08:09:56.573338Z E app: {"#type":"type.googleapis.com/google.cloud.audit.AuditLog","status":{"code":3,"message":"Function failed on loading user code. This is likely due to a bug in the user code. Error message: Error: please examine your function logs to see the error cause: https://cloud.google.com/functions/docs/monitoring/logging#viewing_logs. Additional troubleshooting documentation can be found at https://cloud.google.com/functions/docs/troubleshooting#logging. Please visit https://cloud.google.com/functions/docs/troubleshooting for in-depth troubleshooting documentation."},"authenticationInfo":{"principalEmail":"akhilmodi1988#gmail.com"},"serviceName":"cloudfunctions.googleapis.com","methodName":"google.cloud.functions.v1.CloudFunctionsService.UpdateFunction","resourceName":"projects/pixstory-biz/locations/us-central1/functions/app"}
2022-09-15T08:12:27.847972Z N app: {"#type":"type.googleapis.com/google.cloud.audit.AuditLog","authenticationInfo":{"principalEmail":"akhilmodi1988#gmail.com"},"requestMetadata":{"callerIp":"122.179.194.233","callerSuppliedUserAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.6.1 Safari/605.1.15,gzip(gfe),gzip(gfe)","requestAttributes":{"time":"2022-09-15T08:12:27.950588Z","auth":{}},"destinationAttributes":{}},"serviceName":"cloudfunctions.googleapis.com","methodName":"google.cloud.functions.v1.CloudFunctionsService.DeleteFunction","authorizationInfo":[{"resource":"projects/pixstory-biz/locations/us-central1/functions/app","permission":"cloudfunctions.functions.delete","granted":true,"authorizationLoggingOptions":{"permissionType":"ADMIN_WRITE"},"resourceAttributes":{}}],"resourceName":"projects/pixstory-biz/locations/us-central1/functions/app","request":{"name":"projects/pixstory-biz/locations/us-central1/functions/app","#type":"type.googleapis.com/google.cloud.functions.v1.DeleteFunctionRequest"},"resourceLocation":{"currentLocations":["us-central1"]}}
2022-09-15T08:12:30.436268Z N app: {"#type":"type.googleapis.com/google.cloud.audit.AuditLog","status":{},"authenticationInfo":{"principalEmail":"akhilmodi1988#gmail.com"},"serviceName":"cloudfunctions.googleapis.com","methodName":"google.cloud.functions.v1.CloudFunctionsService.DeleteFunction","resourceName":"projects/pixstory-biz/locations/us-central1/functions/app"}
2022-09-15T08:13:04.366285Z I undefined: {"#type":"type.googleapis.com/google.cloud.audit.AuditLog","authenticationInfo":{"principalEmail":"akhilmodi1988#gmail.com"},"requestMetadata":{"callerIp":"122.179.194.233","callerSuppliedUserAgent":"FirebaseCLI/11.8.0,gzip(gfe),gzip(gfe)","requestAttributes":{"time":"2022-09-15T08:13:04.714274Z","auth":{}},"destinationAttributes":{}},"serviceName":"cloudfunctions.googleapis.com","methodName":"google.cloud.functions.v1.CloudFunctionsService.GenerateUploadUrl","authorizationInfo":[{"resource":"projects/pixstory-biz/locations/us-central1","permission":"cloudfunctions.functions.sourceCodeSet","granted":true,"authorizationLoggingOptions":{"permissionType":"ADMIN_WRITE"},"resourceAttributes":{}}],"resourceName":"projects/pixstory-biz/locations/us-central1","request":{"parent":"projects/pixstory-biz/locations/us-central1","#type":"type.googleapis.com/google.cloud.functions.v1.GenerateUploadUrlRequest"},"response":{"uploadUrl":"https://storage.googleapis.com/uploads-975633983912.us-central1.cloudfunctions.appspot.com/20dd78fd-5c6a-4b23-8d2a-abce039a468e.zip?GoogleAccessId=service-284892888168#gcf-admin-robot.iam.gserviceaccount.com&Expires=1663231384&Signature=o24h25y7yLfKyAzOs8jE8%2BRiXQs9KzeIU2unV6TMBFLYSccAmvzKGB3qk0ps2nXZL0EpBQSAXqhj9nFxTLOWA8AxmS4bD0Z1vBuMpbBNps8mI%2FeY1k5wPnpDdPupG7CLIm%2FHd6H8iXhuF7CTJ7V8C6x%2FIOQP1XiEdOduwoGbUF%2BL9JAn4OpR4JCThIOkCHUu1zkb2lO6otqsfj%2BIYWNQTIJom5c4NgvlzDLFq2sRm2IFSmXhMUa1DVJy7zUEIJVCEdJn1n9MoAQdKqNSC%2BZ5XQSl0uylK5wQI1SyCi%2F32SDEzUK4QZV45dy8XTI2rIOIwdjo7w9s%2BadPzeeDVcN%2FqA%3D%3D","#type":"type.googleapis.com/google.cloud.functions.v1.GenerateUploadUrlResponse"},"resourceLocation":{"currentLocations":["us-central1"]}}
2022-09-15T08:13:04.706769Z I undefined: {"#type":"type.googleapis.com/google.cloud.audit.AuditLog","status":{},"authenticationInfo":{"principalEmail":"akhilmodi1988#gmail.com"},"serviceName":"cloudfunctions.googleapis.com","methodName":"google.cloud.functions.v1.CloudFunctionsService.GenerateUploadUrl","resourceName":"projects/pixstory-biz/locations/us-central1"}
2022-09-15T08:13:06.711244Z N app: {"#type":"type.googleapis.com/google.cloud.audit.AuditLog","authenticationInfo":{"principalEmail":"akhilmodi1988#gmail.com"},"requestMetadata":{"callerIp":"122.179.194.233","callerSuppliedUserAgent":"FirebaseCLI/11.8.0,gzip(gfe),gzip(gfe)","requestAttributes":{"time":"2022-09-15T08:13:07.105263Z","auth":{}},"destinationAttributes":{}},"serviceName":"cloudfunctions.googleapis.com","methodName":"google.cloud.functions.v1.CloudFunctionsService.CreateFunction","authorizationInfo":[{"resource":"projects/pixstory-biz/locations/us-central1/functions/app","permission":"cloudfunctions.functions.create","granted":true,"authorizationLoggingOptions":{"permissionType":"ADMIN_WRITE"},"resourceAttributes":{}}],"resourceName":"projects/pixstory-biz/locations/us-central1/functions/app","request":{"location":"projects/pixstory-biz/locations/us-central1","function":{"entryPoint":"app","name":"projects/pixstory-biz/locations/us-central1/functions/app","httpsTrigger":{"securityLevel":"SECURE_ALWAYS"},"dockerRegistry":"ARTIFACT_REGISTRY","runtime":"nodejs16","labels":{"deployment-tool":"cli-firebase"},"sourceUploadUrl":"https://storage.googleapis.com/uploads-975633983912.us-central1.cloudfunctions.appspot.com/20dd78fd-5c6a-4b23-8d2a-abce039a468e.zip?GoogleAccessId=service-284892888168#gcf-admin-robot.iam.gserviceaccount.com&Expires=1663231384&Signature=o24h25y7yLfKyAzOs8jE8%2BRiXQs9KzeIU2unV6TMBFLYSccAmvzKGB3qk0ps2nXZL0EpBQSAXqhj9nFxTLOWA8AxmS4bD0Z1vBuMpbBNps8mI%2FeY1k5wPnpDdPupG7CLIm%2FHd6H8iXhuF7CTJ7V8C6x%2FIOQP1XiEdOduwoGbUF%2BL9JAn4OpR4JCThIOkCHUu1zkb2lO6otqsfj%2BIYWNQTIJom5c4NgvlzDLFq2sRm2IFSmXhMUa1DVJy7zUEIJVCEdJn1n9MoAQdKqNSC%2BZ5XQSl0uylK5wQI1SyCi%2F32SDEzUK4QZV45dy8XTI2rIOIwdjo7w9s%2BadPzeeDVcN%2FqA%3D%3D"},"#type":"type.googleapis.com/google.cloud.functions.v1.CreateFunctionRequest"},"resourceLocation":{"currentLocations":["us-central1"]}}[![enter image description here][1]][1]
index.js
const functions = require("firebase-functions");
// const admin = require('firebase-admin');
// admin.initializeApp();
const express = require('express');
//require('./db/mongoose');
require('../db/mongoose');
//const notification = require('./db/models/notification');
var bodyParser = require('body-parser');
const app = express();
const userprofileInformation = require('../routers/userprofileinfo');
const userCampaigninformation = require('../routers/userProjectInformation');
const searchPerson = require('../routers/search');
const filter = require('../routers/filter');
const multer = require('multer');
const jwt = require('jsonwebtoken');
const http = require('http').createServer(app);
let fs = require('fs');
const loginDetails = require('../routers/login_page');
//const jwt = require('jsonwebtoken');
const UserController = require('../routers/user_controller');
require('dotenv').config();
const filterPage = require('../routers/filter');
var cors = require("cors");
var cookieParser = require('cookie-parser');
var path = require('path');
const controller = require('../controllers/razorpay_controller');
const excelToJson = require('convert-excel-to-json');
const userProfile = require('../models/search');
const issueRaiseUser = require('../routers/user_issue');
app.use(cors());
const portCheck = process.env.PORT || 3001
app.use(express.json({limit: "50mb"}));
app.use(express.urlencoded({limit: "50mb", extended: true}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, '../pix/public-flutter')));
app.get('/', (_, res) => {
res.sendFile(path.resolve(__dirname, '../pix/public-flutter/index.html'));
});
app.use(UserController);
app.use(userprofileInformation);
app.use(userCampaigninformation);
app.use(filter);
app.use(issueRaiseUser);
//app.use(searchPerson);
exports.app = functions.https.onRequest(app);
package.json
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"serve": "firebase emulators:start --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "16"
},
"main": "index.js",
"dependencies": {
"bcryptjs": "^2.4.3",
"convert-excel-to-json": "^1.7.0",
"cookie-parser": "^1.4.6",
"cors": "^2.8.5",
"dotenv": "^16.0.1",
"express": "^4.18.1",
"firebase-admin": "^10.0.2",
"firebase-functions": "^3.18.0",
"JSONStream": "^1.3.5",
"jsonwebtoken": "^8.5.1",
"mongoose": "^6.3.1",
"mongoose-sequence": "^5.3.1",
"multer": "^1.4.4",
"n": "^9.0.0",
"natural": "^5.2.3",
"node-nlp": "^4.24.0",
"nodemailer": "^6.7.5",
"otp-generator": "^4.0.0",
"razorpay": "^2.8.1",
"remove-stopwords": "^1.0.3",
"stable": "^0.1.8",
"stopword": "^2.0.2",
"stripe": "^9.11.0",
"twilio": "^3.78.0",
"validator": "^13.7.0"
},
"devDependencies": {
"firebase-functions-test": "^0.2.0"
},
"private": true
}
File structure:
[![Files][2]][2]
[2]: https://i.stack.imgur.com/6BGj7.png

Proxy Routing on Angular App deployed on Heroku

I have an Angular app that is talking to a REST service.
When I run the Angular app local with the CLI, correctly proxies all /api requests to the REST service. When I try to build the app and run through a server.js (so that I can deploy the app to Heroku) I lose the proxy routing.
The REST service is deployed on Heroku and runs fine.
I run the Angular with:
ng serve
My proxy.conf.json
{
"/api": {
"target": "https://my-app.herokuapp.com",
"secure": true,
"changeOrigin": true
}
}
I created a server.js as described in this article so that I can deploy onto Heroku.
// server.js
const express = require('express');
const app = express();
const path = require('path');
// If an incoming request uses
// a protocol other than HTTPS,
// redirect that request to the
// same url but with HTTPS
const forceSSL = function () {
return function (req, res, next) {
if (req.headers['x-forwarded-proto'] !== 'https') {
return res.redirect(
['https://', req.get('Host'), req.url].join('')
);
}
next();
}
}
// Instruct the app
// to use the forceSSL
// middleware
app.use(forceSSL());
// Run the app by serving the static files
// in the dist directory
app.use(express.static(__dirname + '/dist'));
// For all GET requests, send back index.html
// so that PathLocationStrategy can be used
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname + '/dist/index.html'));
});
// Start the app by listening on the default
// Heroku port
app.listen(process.env.PORT || 4200);
I also set up a post install build in my package.json scripts:
{
"name": "catalog-manager-client",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "node server.js",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e",
"postinstall": "ng build --aot"
},
"private": true,
"dependencies": {
"#angular/animations": "^6.0.3",
"#angular/cdk": "^6.2.1",
"#angular/cli": "~6.0.8",
"#angular/language-service": "^6.0.3",
"#angular/common": "^6.0.3",
"#angular/compiler": "^6.0.3",
"#angular/compiler-cli": "^6.0.3",
"#angular/core": "^6.0.3",
"#angular/flex-layout": "^6.0.0-beta.16",
"#angular/forms": "^6.0.5",
"#angular/http": "^6.0.3",
"#angular/material": "^6.2.1",
"#angular/platform-browser": "^6.0.3",
"#angular/platform-browser-dynamic": "^6.0.3",
"#angular/router": "^6.0.3",
"#swimlane/ngx-charts": "^8.0.2",
"#swimlane/ngx-datatable": "^13.0.1",
"core-js": "^2.5.4",
"express": "^4.16.4",
"hammerjs": "^2.0.8",
"jquery": "^3.3.1",
"moment": "^2.22.2",
"ngx-perfect-scrollbar": "^6.2.0",
"ngx-quill": "^3.2.0",
"rxjs": "^6.0.0",
"rxjs-compat": "^6.2.1",
"rxjs-tslint": "^0.1.4",
"zone.js": "^0.8.26"
},
"devDependencies": {
"#angular-devkit/build-angular": "~0.6.8",
"typescript": "~2.7.2",
"#types/jasmine": "~2.8.6",
"#types/jasminewd2": "~2.0.3",
"#types/node": "~8.9.4",
"codelyzer": "~4.2.1",
"jasmine-core": "~2.99.1",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~1.7.1",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "~2.0.0",
"karma-jasmine": "~1.1.1",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~5.3.0",
"ts-node": "~5.0.1",
"tslint": "~5.9.1"
},
"engines": {
"node": "9.11.2",
"npm": "6.5.0"
}
}
I am an Angular novice so I could be making a fundamental mistake, but how do I modify the server.js to use the proxy.conf.json settings?
The explanation falls into the yes, you're making a fundamental mistake category, but I've seen enough similar questions that I thought an explanation might just help the next dev.
The Angular CLI is running a full http server. The Angular UI is fully compiled and the CLI is serving it as static content from the /dist directory.
The proxy.conf.json settings are for the Server run by the Angular CLI, it has nothing to do with your compiled code.
When you move from a local environment to something like Heroku you need a server to take the place of the Angular CLI. This is where all the examples of node.js and express come in. The simple server.js file they walk you through is enough to set up a basic static content server. And that's fine, because your Angular code is static content!
But if you need routing to a dynamic backend server via a proxy.conf.json, well, your simple static server doesn't know anything about that.
In my case, my backend server runs on Koa, so I added static routing to the Angular code.
const router = require('koa-router')();
const body = require('koa-body')({ text: false });
const send = require('koa-send');
const fs = require('fs');
/**
* Code about server routes ommited
*/
async function main(ctx, next) {
//All dynamic routes start with "/api"
if (/\/api\//.test(ctx.path)) {
try {
await next();
}
catch (error) {
if (error instanceof ApplicationError) {
logger.error(error, { data: error.data, stack: error.stack });
ctx.status = error.code;
} else {
ctx.status = 500;
logger.error(error.message, { stack: error.stack });
}
}
return;
} else {
//Not a dynamic route, serve static content
if ((ctx.path != "/") && (fs.existsSync('dist' + ctx.path))) {
await send(ctx, 'dist' + ctx.path);
} else {
await send(ctx, 'dist/index.html');
}
}
}
module.exports = app => {
app.use(main);
app.use(router.routes());
};
NOTE - this isn't a performant solution for any kind of high workload, but if you've got a very small project that doesn't justify spending resources setting up something more scalable, this will work until you get bigger.
Any One looking for Implementation of angular application using proxy api on heroku you can use WebpackDev Server and http-proxy-middleware in server.js
npm install http-proxy-middleware
npm install webpack webpack-dev-server
webpack.config.js
const path = require('path');
module.exports = {
entry:'./src/index.js',//no implemenation needed by default webpack verification
mode: 'development',
devServer: {
historyApiFallback: true,// handle 404 cannot get error after refreshing url
https: true,//secure the server
compress: true,//invalid header multiple url proxy
client: {
webSocketURL: 'ws://0.0.0.0:8080/ws',// handle Invalid header error in heroku port 8080 maps in server.js
},
static: {
directory: path.join(__dirname, '/dist/<app-name>'),
},
proxy: {
/** Same as proxy.conf.json or proxy.conf.js */
' /api1/*': {
target: 'https://<other-heroku-deployed-url>',
changeOrigin:true,
secure:false,
pathRewrite: {
'^/api1':'https://<other-heroku-deployed-url>/api1' },
},
' /api2/*': {
target: 'https://<other-heroku-deployed-url>',
changeOrigin:true,
secure:false,
pathRewrite: {
'^/api2':'https://<other-heroku-deployed-url>/api2' },
}
},
},
};
server.js
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();
const Webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
/** this is custom js to help proxy in server.js*/
const webpackConfig = require('./webpack.config.js');
const compiler = Webpack(webpackConfig);
const devServerOptions = { ...webpackConfig.devServer, open: true };
const server = new WebpackDevServer(devServerOptions, compiler);
const runServer = async () => {
console.log('Starting server...');
await server.start();
};
runServer();
/** If you have error creating proxy <app-url> to localhost
* Heroku internally redirect the Server port 8080 .
* For that reason we need to open listener port(I used 3000 here) redirect
through http-proxy-middleware*/
app.use("/*", createProxyMiddleware(
{ target: "https://localhost:8080",
ws: true ,
changeOrigin: true,
secure:false,
router: {
'dev.localhost:3000': 'https://localhost:8080',
},}))
app.listen(process.env.PORT || 3000)
npm start or node server.js

Nodejs does not recognize my server.js paths

I'm trying to run the yarn start_dev command inside my main directory C:\Users \THIAGOSAAD\Documents\DEVELOPMENT\NEORIS\ALIANSCE\aliansce-app-analyticals-panel
However when doing this it starts to give error in my "process.env.DATABASE_URL" as if it did not recognize my "dotenv" that is in the "environment" folder!
consign v0.1.6 Initialized in C:\Users\THIAGOSAAD\Documents\ DEVELOPMENT\NEORIS\ALIANSCE\aliansce-app-analyticals-panel
C:\Users\THIAGOSAAD\Documents\DEVELOPMENT\NEORIS\ALIANSCE\aliansce-app-analyticals-panel\node_modules\mongoose\lib\connection.js: 428
throw new MongooseError ('The `uri` parameter to` openUri () `must be a +
^
MongooseError: The `uri` parameter to` openUri () `must be a string, got" undefined ". Make sure the first parameter to `mongoose.connect ()` or `mongoose.createConnection ()` is the string.
at new MongooseError (C: \Users\THIAGOSAAD\Documents\DEVELOPMENT\ NEORIS\ALIANSCE\aliansce-app-analyticals-panel\node_modules\mongoose\lib\ error\mongooseError.js: 13:11)
at NativeConnection.Connection.openUri (C:\Users\THIAGOSAAD\Documents\ DEVELOPMENT\NEORIS\ALIANSCE\aliansce-app-analyticals-panel\node_modules\ mongoose\lib\connection.js: 428:11)
at Mongoose.connect (C:\Users\THIAGOSAAD\Documents\DEVELOPMENT\ NEORIS \ ALIANSCE\aliansce-app-analyticals-panel\node_modules\mongoose\lib\ index.js: 270: 15)
If I enter the url directly on my server.js it starts to give errors in my consign:
consign v0.1.6 Initialized in C:\Users\THIAGOSAAD\Documents\DEVELOPMENT \NEORIS\ALIANSCE\aliansce-app-analyticals-panel
! Entity not found C:\Users\THIAGOSAAD\Documents\DEVELOPMENT\NEORIS\ALIANSCE\aliansce-app-analyticals-panel\routes
! Entity not found C:\Users\THIAGOSAAD\Documents\DEVELOPMENT\NEORIS\ ALIANSCE \ aliansce-app-analyticals-panel\controllers
SERVER ROLLING IN PORT 3000: ')
But if I run the nodemon from the directory where the start.js is, it works: C: \Users\THIAGOSAAD\Documents\DEVELOPMENT\NEORIS\ALIANSCE\aliansce-app-analyticals-panel\app\backend\src\start.js
I would like to know why this happens and how to solve it, because I'm trying to upload the server to Heroku and it's not running, probably because of the same problem running yarn start_dev!
MY DIRECTORIES
SERVER.JS
const express = require('express');
const dotenv = require('dotenv');
const morgan = require('morgan');
const consign = require('consign');
const mongoose = require('mongoose');
const nunjucks = require('nunjucks');
class Application {
constructor(){
this.express = express();
this.dotenv = dotenv.config({ path: './environment/.env' });
this.morgan = morgan('dev');
this.consign = consign();
this.mongoose = mongoose;
this.nunjucks = nunjucks;
// INICIALIZA AS FUNÇÕES AUTOMATICAMENTE
this.initDatabase();
this.initMiddlewares();
this.initConsign();
this.initViews();
}
initDatabase(){
this.mongoose.connect(process.env.DATABASE_URL, {
useCreateIndex: true,
useNewUrlParser: true
});
}
initMiddlewares(){
this.express.set('view engine', 'njk');
this.express.use(express.static('../../app/frontend'));
this.express.use(express.json());
this.express.use(express.urlencoded({ extended: true }));
this.express.use(this.morgan);
}
initConsign(){
this.consign.include('./routes').then('./controllers').into(this.express);
}
initViews(){
this.nunjucks.configure('./views/pages', {
watch: true, // SOMENTE PARA DESENVOLVIMENTO
express: this.express,
autoescape: true
});
}
}
module.exports = new Application().express;
PACKAGE.JSON
{
"author": "THIAGO DE BONIS CARVALHO SAAD SAUD",
"scripts": {
"start_dev": "nodemon app/backend/src/start.js"
},
"dependencies": {
"axios": "^0.18.0",
"bootstrap": "^4.2.1",
"bootstrap-select": "^1.13.5",
"chartjs": "^0.3.24",
"consign": "^0.1.6",
"dotenv": "^6.2.0",
"express": "^4.16.4",
"express-validator": "^5.3.1",
"jquery": "^3.3.1",
"jsonwebtoken": "^8.4.0",
"mongoose": "^5.4.1",
"nunjucks": "^3.1.6"
},
"devDependencies": {
"morgan": "^1.9.1",
"nodemon": "^1.18.9"
}
}
When setting the dotenv folder path set the absolute path.
this.dotenv = dotenv.config({ path: require('path').join(__dirname, './environment') });

Heroku Deployment Nodejs

I developed a app using react, mongodb, express, nodeJS. I am able to run the app perfectly in my desktop. I have run express & react on different ports. But this doesn't work when I deploy it to heroku.
server.js
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
var Schema = mongoose.Schema;
var session = require('express-session');
var cookieParser = require('cookie-parser');
var cors=require('cors');
//setup express app
const app = express();
app.use(cors());
//connect to mongodb
mongoose.connect(process.env.MONGODBURI);
mongoose.Promise = global.Promise;
//connect public folder
app.use(express.static('public'));
//bodyparser middleware
app.use(bodyParser.json());
//routes middleware
app.use(cookieParser())
app.use(session({secret: 'MySecret'}));
app.use('/userapi',require('./routes/userapi.js'));
app.use('/cde',require('./routes/cde.js'));
app.use('/efg',require('./routes/efg.js'));
//error handler middleware
app.use(function(err,req,res,next){
res.status(422).send({error: err.message});
});
const port = process.env.PORT || 8080;
app.listen(port, () => {
console.log('Express server listening on port', port)
});
package.json
{
"name": "vip",
"version": "0.1.0",
"private": true,
"dependencies": {
"afterglow": "0.0.3",
"afterglowplayer": "^1.1.0",
"axios": "^0.17.1",
"body-parser": "^1.18.2",
"cookie-parser": "^1.4.3",
"cookieparser": "^0.1.0",
"cors": "^2.8.4",
"express": "^4.16.2",
"express-session": "^1.15.6",
"foreman": "^2.0.0",
"fs": "0.0.1-security",
"gifffer": "^1.5.1",
"glamor": "^2.20.40",
"image-map-resizer": "^1.0.3",
"jquery": "^3.3.1",
"marked": "^0.3.12",
"mongoose": "^5.0.1",
"natural": "^0.5.6",
"react": "^16.2.0",
"react-data-menu": "^1.1.1",
"react-dom": "^16.2.0",
"react-gif": "^0.1.0",
"react-modal": "^3.1.13",
"react-scripts": "1.1.0",
"react-toastify": "^3.4.2",
"redux": "^3.7.2",
"shelljs": "^0.8.1",
"video-react": "^0.9.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"devDependencies": {
"nodemon": "^1.14.12",
"react-router-dom": "^4.2.2"
}
}
I've pushed all the code to heroku and I've set the mongodb uri to mlab in heroku dashboard settings. When I request express it gives me a error
GET https://myappname.herokuapp.com/userapi/verifylogin?email=aa&password=aa 404 (Not Found)
createError.js:16 Uncaught (in promise) Error: Request failed with status code 404
at createError (createError.js:16)
at settle (settle.js:18)
at XMLHttpRequest.handleLoad (xhr.js:77)
userapi`
const express = require('express');
const router = express.Router();
const User = require('../models/Login');
const LoginSession = require('../models/LoginSession');
const server = require('../server');
//find a record matching username & Password
router.get('/verifylogin',function(req,res,next){
User.findOne({email:req.query.email,password:req.query.password}).then(function(sequence_data){
res.send(sequence_data);
});
});
module.exports = router;
`
I've gone through many other posts related, but didn't resolved it.

Issue running Next.js on iisnode on Azure Web App

Trying to deploy and run Next.js on Azure Web App. Azure Web App works when running just with Express.js but as soon as I call nex() it fails. Tried to enable the error logging in Azure portal but not much of any use came out, just generic 500 errors.
Below is what works and what doesn't.
Works:
var express = require('express');
var expressServer = express();
expressServer.get('/', function (req, res) {
res.send('Express is working on IISNode!');
});
expressServer.listen(process.env.PORT || 8080);
Does not work:
var express = require('express');
const next = require('next');
var expressServer = express();
var app = next();
expressServer.get('/', function (req, res) {
res.send('Express is working on IISNode!');
});
expressServer.listen(process.env.PORT || 8080);
I don't even bother getting request handler at this point as the app = next() is failing.
Package.json:
"engines": {
"node": "9.4.0 || 8.9.x"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.16.2",
"next": "^4.2.3",
"next-redux-wrapper": "^1.3.5",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-redux": "^5.0.6",
"redux": "^3.7.2",
"redux-thunk": "^2.2.0"
},
"devDependencies": {
"babel-preset-es2015": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"nodemon": "^1.14.11"
}
EDIT:
I believe the issue is that next build needs to run first. I am looking if I can add some post deployment/build command with something like Kudu. If you have any suggestions please let me know.
You are right, you need to run next build first.
So, this would work in Azure Web App if you create pages directory under project root and edit the package.json to add this:
"scripts": {
"postinstall": "next build"
}

Resources