Express app - Host on Heroku and use Parse as backend - node.js

For my express app I want to use Parse to handle all my data. As Parse's hosting options for web apps seem very limited (caped at 500 files and 500MB), I want to use Heroku to host my app. I have managed to set up my express app on Heroku, but can not quite figure out how to get access to my Parse app in it. I've searched around, but there does not seem to be too much documentation on this, and I am struggling to get it to work.
Here is my index.js for my express app:
var express = require('express');
var bodyParser = require('body-parser')
var app = express();
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
// views is directory for all template files
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.get('/', function(request, response) {
response.render('pages/public');
});
app.get('/login', function(request, response) {
response.render('pages/login');
});
// Clicking submit on the login form triggers this.
app.post('/login', function(req, res) {
Parse.User.logIn(req.body.username, req.body.password).then(function() {
// Login succeeded, redirect to homepage.
res.redirect('pages/loggedin');
},
function(error) {
// Login failed, redirect back to login form.
res.redirect('pages/login');
});
});
In app.post('/login'I have the Parse function I would use to log in users, but as Parse is not connected it just throws an error. How do I let my Express app get data from Parse?
My package.json files looks like so:
{
"name": "node-js-getting-started",
"version": "0.1.4",
"description": "A simple Node.js app using Express 4",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"ejs": "^2.3.1",
"express": "~4.9.x",
"body-parser": "1.13.x"
},
"engines": {
"node": "0.12.2"
},
"repository": {
"type": "git",
"url": "https://github.com/heroku/node-js-getting-started"
},
"keywords": [
"node",
"heroku",
"express"
],
"license": "MIT"
}
Thanks for any help!

Another hour of googling and I came across these links which proved useful:
https://medium.com/#spacekid/getting-started-with-parse-node-js-express-b2c79798cc7d
http://blog.parse.com/learn/engineering/the-javascript-sdk-in-node-js/

Before using Parse.User.logIn() and so on (or any other node.js module), you must make sure you actually include it like you include bodyParser module.
For example:
var Parse = require('node-parse-api').Parse;
Have a look at this module: Node Parse API

Related

Firebase - Cloud Functions not running when deployed

I'm developing a blog application with firebase. I'm using express with ejs on this project.
PROBLEM - The project is working perfectly when I run them using the emulator, but doesn't work on firebase's hosting.
I've tried changing my code and re-deploying all the files many times. The function is visible in the 'functions' tab in firebase, and doesn't log any errors when I open the page.
I've checked the following ->
1) Firebase functions SDK, npm modules, and the CLI updated to the latest version.
// >>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": "10"
},
"dependencies": {
"ejs": "^3.1.3",
"express": "^4.17.1",
"firebase-admin": "^8.10.0",
"firebase-functions": "^3.7.0"
},
"devDependencies": {
"firebase-functions-test": "^0.2.0"
},
"private": true
}
2) The project is running on node 10.
3) I've added rewrites to my function in firebase.json
//>>firebase.json<<
"firestore": {
"rules": "firestore.rules",
"indexes": "firestore.indexes.json"
},
"hosting": {
"public": "public",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [ {
"source": "**",
"function": "app"
} ]
},
4) Tried the Port Numbers, and cross-checked other essential configurations.
5) My project is linked to google cloud, which has an active payment account.
6) Works fine when tested locally in a firebase emulator.
This is my function
// >>index.js<<
const functions = require('firebase-functions');
const express = require('express');
const app = express(); // express initialize
//firestore
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();
app.listen(443); // listen for requests
// register view engine
app.set('view engine', 'ejs');
app.set('views', './views');
// middleware & static files
app.use(express.static('stats'));
// HANDLING REQUESTS
app.get('/', (req, res) => {
res.render('index', { title: "Blog by Zeal For Good" });
})
app.get('/index', (req, res) => {
res.redirect('/');
})
app.use((req, res) => {
res.status(404).render('404', { title: '404' });
});
exports.app = functions.https.onRequest(app);
I'm getting this message when I'm opening my website (https://zealforgood-blog.web.app/) ->
Install Express on 'functions' folder.
Install all modules that you need of the ExpressJs on 'functions' folder.
The Firebase with Cloud Functions need 'Cors' module running in ExpressJs. Install it.
The System needs a 'public' folder on project's base folder, another 'public' folder on the 'functions' folder.
After, run 'npm install' in project's base folder and on the 'fuctions' folder
delete 'index.html' and '404.html' on the 'public' folders genereted for Default by Firebase
change your files .html to .ejs;
Adjust your project like this:
// in firebase.json use: //
"source": "/**",
// in index.js: //
const cors = require('cors');
...
const app = express();
...
// set view engine setup EJS
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// set this line below too
app.engine('ejs', require('ejs').__express);
app.use(cors({ origin: true }));
Note: This line below is a copy from the japanese site that do EJS render on Cloud Functions (https://qiita.com/kingpanda/items/aa9bdef2706857720058).
app.engine('ejs', require('ejs').__express);
Works to me!
Good Luck!

Failed at the app#1.0.0 start script This is probably not a problem with npm. There is likely additional logging output above

Hi Guys, I have created a little project of Mern stack. I am deploying it correctly on Heroku. But as soon as I am checking her on Heroku after deploying, then Failed to load resource: the server responded with a status of 503 (Service Unavailable) error is coming.
But as soon as I run heroku local in cmd after deploying then it is working correctly. I am giving below the heroku setup code. Please guide me. please ........
package.sjon file of backend
{
"name": "app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "npm install && node index",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
},
"dependencies": {
"config": "^3.3.1",
"express": "~4.16.1",
"express-fileupload": "^1.1.7-alpha.3",
"mongoose": "^5.9.12",
"nodemailer": "^6.4.6"
},
"keywords": [],
"author": "",
"license": "ISC"
}
Index.js file of backend
var express = require('express');
var path = require('path');
const connectDB = require('./config/db')
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var studentRouter = require('./routes/student')
var app = express();
connectDB();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static('client/build'))
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'))
})
app.use('/', indexRouter);
app.use('/', studentRouter);
app.use('/users', usersRouter);
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'))
})
}
var port = process.env.PORT || '8000';
app.listen(port, () => {
console.log(`server run port ${port}`);
})
module.exports = app;
All these codes are absolutely correct. I had a problem creating a cluster in mongodb atlas. The problem was that I had selected add current ip address while creating the cluster. Whereas I had to select allow from anywhere. So now I have selected the book. And now it is doing the right thing.
In my case, changing network access form anywhere in my MongoDB cluster, fixed the problem.
Also, don't forget to hit restart all dynos.

Fb developer issue - 'URL couldn't be validated. Response does not match expected challenge'

I've launched a Heroku application using the following files:-
app.js
'use strict'
const express = require('express')
const bodyParser = require('body-parser')
const request = require('request')
const app = express()
app.set('port', (process.env.PORT || 5000))
// Process application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: false}))
// Process application/json
app.use(bodyParser.json())
// Index route
app.get('/', function (req, res) {
res.send("Hello world, I seem to be working")
})
// for Facebook verification
app.get('/webhook', function (req, res) {
if (req.query['hub.verify_token'] === 'test-token') {
res.send(req.query['hub.challenge']);
} else {
res.send('Error, wrong validation token');
}
})
// Spin up the server
app.listen(app.get('port'), function() {
console.log('running on port', app.get('port'))
})
.gitignore
node_modules
package.json
{
"name": "heroku-node-practice",
"version": "1.0.0",
"description": "New bot",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node app.js"
},
"author": "Paigal",
"license": "ISC",
"dependencies": {
"body-parser": "^1.17.1",
"express": "^4.15.2",
"foobar": "^1.1.0",
"mongoose": "^4.9.8",
"request": "^2.81.0"
}
}
Procfile
web: node app.js
I installed node.js dependencies using the command: npm install express request body-parser --save
After git push heroku master, the application launches correctly.
However, when trying to set up a webhook in fb developer, the error is 'URL couldn't be validated. Response does not match expected challenge' then gives the different responses to the challenge. That is, my URL responds with "Hello world, I seem to be working" instead of numerical key.
Would greatly appreciate your help!
You need to point FB to the route that has the verify function within it. You are currently pointing FB to the site root index '/' it seems.
Change the FB webhook url in the app settings to https://YOUR_DOMAIN.com/webhook and the verification will be complete. FB will then send whatever events you subscribe to to your '/webhook' route.
If this doesn't work, notice you have hardcoded your verify token here as test-token:
...
if (req.query['hub.verify_token'] === 'test-token') { ...
This will only complete the challenge if 'test-token' is what you set your webhook verification token to. A better way to do this imo would be the following:
...
if (req.query['hub.verify_token'] === process.env.VERIFY_TOKEN ) { ...
In the above example you must pass in the verify token you choose for your webhook when running your server, before you try to verify the webhook.
In your heroku dashboard, add VERIFY_TOKEN with your token as the value to your config variables. This will make the verify token available without hardcoding.

Express js render : TypeError: this.engine is not a function [duplicate]

This question already has answers here:
How do I use HTML as the view engine in Express?
(16 answers)
Closed 5 years ago.
I am getting TypeError: this.engine is not a function. I don`t know why I am getting this error. Can anyone please help me to solve this issue.
My server file:
var express = require('express');
var path = require('path');
var app = express();
//configure app
app.set('view engine', 'html');
app.set('views', path.join(__dirname, 'views'));
app.get('/', function (req, res) {
res.render('index');
});
app.listen(3000, function() {
console.log('Ready on port 1337');
});
And my HTML file:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>Hello Express</div>
</body>
</html>
I get the error
My package.json:
{
"name": "app",
"version": "1.0.0",
"main": "index.html",
"directories": {
"test": "test"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "mehadi",
"license": "UNLICENSED",
"dependencies": {
"express": "4.13.0",
"html": "^1.0.0"
},
"repository": {
"type": "git",
"url": "(github.com/mehadi07/Random.git)"
},
"devDependencies": {},
"description": ""
}
I installed the html engine via
npm install --save html
The html package you've installed is unrelated to Express. So it's not surprising that if you tell Express to use it, it fails.
If you're looking to serve static HTML files, see this question's answers, and the Express documentation. The simplest way is just
app.use(express.static('views'));
html package is not a template engine that can be used with Express. Instead it is a HTML pretty printer CLI utility.
Please see Using template engines with Express for a list of template engines that works fine with Express.

Nodejs Heroku Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch

I have tried number of "Error R10" Solutions, but it doesn't solve the problem for a simple Hello World like Nodejs app with server.js, package.json, index.html and node_module
Hereby adding server.js, package.json and error log
Currently trying this app on free heroku acount
Is it necessary to upload nodejs app on github to host it on heroku
server.js
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var port = 3000;
var app = express();
// Set Static Folder
app.use(express.static(__dirname));
// Body Parser MW
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
var env = process.env.NODE_ENV || 'development';
if ('development' == env) {
app.use(express.static(__dirname + '/'));
} else {
app.use(express.static(__dirname + '/'));
}
app.get("/", function(req, res){
res.render("index.html");
});
app.listen(port, function(){
console.log("Server started ..!");
});
package.json
{
"name": "es1",
"version": "1.0.0",
"description": "eS",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.16.0",
"express": "^4.14.0"
}
}
Attaching heroku logs:
https://drive.google.com/open?id=0B4XtAe7mRM6UVllTQWh1dmplZk0
Change the value of port as follows:
var port = process.env.PORT || 3000;

Resources