How to deploy my Nodejs application on my webpage? - node.js

Made a very simple Timestamp Microservice app with node that I want to be able to run on a webpage on my website. How would I go about doing this? It currently works fine on my local server.
I feel like this would be very simple but from searching can only find how to deploy to Heroku/AWS.
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
//Create an instance of Express for the app and instantiate bodyParser and cors
const app = module.exports = express();
app.use(bodyParser.json());
app.use(cors());
app.get(`/dateValues/:dateVal`, (req,res,next) => {
//gets date from request
var dateVal = req.params.dateVal;
//Options for formatting date in natural state
var options = { year: 'numeric', month: 'long', day: 'numeric' };
if(isNaN(dateVal)) {
var naturalDate = new Date(dateVal);
naturalDate= naturalDate.toLocaleDateString('en-US', options);
var unixDate = new Date(dateVal).getTime()/1000-21600;
} else {
var unixDate = dateVal;
var naturalDate = new Date((parseInt(dateVal)+21600)*1000);
naturalDate= naturalDate.toLocaleDateString('en-US', options);
}
res.json({unix: unixDate, natural: naturalDate});
});
app.listen(3000, () => {
console.log('App is running');
});

is you want to push this online on your own server, it will be the same as you did in local.
Install your server, install npm/node, push your project on it and run npm start. This will work.
If you want something a bit better for production, you can use a proxy webserver, like apache or nginx and run your nodejs project with pm2
https://www.phusionpassenger.com/library/walkthroughs/deploy/nodejs/ownserver/nginx/oss/trusty/deploy_app.html

Heroku is the easiest deployment platfrom when it comes to node.js application. You can host it for free too. Checkout the url below.
https://devcenter.heroku.com/articles/getting-started-with-nodejs#introduction

Related

Combine node.js rest api's and angular on same server

We first developed REST api's using node.js and have that running on a VPS. We now have developed an Angular web app to display data that comes in via a mobile app that calls some of the REST api's and then updates the data by calls back to other REST API's. Running the Angular app on the localhost was able to successfully call the REST api's.
We want to combine both applications on the same server. After searching around it seemed that we could add commands to the REST api server.js to pass urls that didn't meet the REST api path to Angular. Code snippet is below:
// API verison
var apiVersion = '/v1'
var fs ;
var https ;
// Dependencies
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
// MongoDB
...
// Express
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Routes
app.use(apiVersion, require('./routes/api'));
// Start server
fs = require('fs')
https = require('https')
https.createServer({
key: fs.readFileSync('...'),
cert: fs.readFileSync('...')
}, app)
.listen(443, function () {
console.log('HTTPS Server running on default port 443')
});
// Pass request to angular?
app.use(function(req, res) {
var path = require('path');
res.sendfile(path.resolve('/home/.../index.html')); // but not getting anything
});
The REST api's still work but when directing a browser to 'mydomain.net' I just get a blank page. I don't see any errors on the node/error logs.
Any ideas?
You can do something like this. Use static content to send from the dist folder and rest will work fine. I have added two reference in case you might need them to refer.
var apiVersion = '/v1'
const fs = require('fs')
const https = require('https');
const path = require('path')
// Dependencies
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
// MongoDB
...
// Express
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Pass request to angular?
app.use('path', express.static(path.resolve('your path should be correct')));
// Routes
app.use(apiVersion, require('./routes/api'));
// Start server
https.createServer({
key: fs.readFileSync('...'),
cert: fs.readFileSync('...')
}, app)
.listen(443, function () {
console.log('HTTPS Server running on default port 443')
});
Check here1 or here2 for more details, there are simple steps to follow.

Can´t connect to heroku PostgreSQL database with Node.js and Express, no error is showing

So i recently created an Account at heroku.com and created a PostgreSQL database. First of all i wanted to test if i could store something into the database (One table was already created without node.js) but for some odd reason the callback function of my dbClient.query never executed. I then realized that the Database does not connect to my code. My password, host, etc. should all be right and i can connect from extern sites but not from my node.js code.
Here´s my code:
var express = require("express");
var pg = require("pg");
var bodyParser = require("body-parser");
var CON_STRING = process.env.DB_CON_STRING;
if (CON_STRING == undefined) {
console.log("Error: Environment variable DB_CON_STRING not set!");
process.exit(1);
}
pg.defaults.ssl = true;
var dbClient = new pg.Client(CON_STRING);
dbClient.connect();
var urlencodedParser = bodyParser.urlencoded({
extended: false
});
var PORT = 3000;
var app = express();
app.set("views", "views");
app.set("view engine", "pug");
app.get("/shoppingitems", function (req, res) {
res.render("shoppingitems")
});
app.post("/shoppingitems", urlencodedParser, function(req, res){
var shoppingItem = req.body.shoppingItem;
dbClient.query("INSERT INTO shoppinglist (title) VALUES ($1)", [shoppingItem], function(dbError, dbResponse){
console.log("function called!");
res.redirect("/shoppingitems");
})
console.log("test");
})
app.listen(PORT, function () {
console.log(`Shopping App listening on Port ${PORT}`);
});
It does not work with other configs of dbClient.query.
You need to set the environment variable on your localhost, depending on your OS.
For Mac & Linux use 'export' keyword in Terminal for YOUR_ENV_VAR, example:
export DB_CON_STRING=postgres://ufohlgoihdgfalr:2fb913jhazsxd541469b972fcac862ddf664620998e87c96787569poiude4ab0b#ec2-34-238-26-109.compute-1.amazonaws.com:5432/d587yhytte32gj
You can check your variable using 'echo' and $ sign in Mac and Linux, for example
echo $DB_CON_STRING
It should give you the string if the variable is set or not.
Note that will be only work for the current session in the Terminal, if you want to keep it and use it for a long time or after closing/opening the terminal then it is better to add it to your .bash_profile. Same way, just make it saved in the /uerMacUser/.bash_profile
For windows you can do it using GUI, for quick access use in 'Run' rundll32.exe sysdm.cpl,EditEnvironmentVariables
Heroku Postgres uses different environment variable named 'DATABASE_URL' so you might want to consider this if you want to deploy on heroku later, otherwise your application will not start on heroku.

Node.JS Application - Tasks and API

General question.
I am looking to create a console-like application with Node.js that also has api capabilities. It will have timed task that will run on a schedule but also be available to send http request to. My problem is that while I've created the api. I don't know how to go about creating basic task to be performed on a schedule while the server stays running in case http request is made for different types of task.
Main idea is to have the task schedule to run while also keeping the server running and waiting for http request
Folder paths
folders
-controllers
-models
-modules
-node-modules
-routes
general files
app.js
package-lock.json
package.json
server.js
task.js
Proposed area for Scheduled task to be performed:
index.js
const { checkTablesForData, requestRoutine, runNecessaryUpdate } = require('./task')
function Main() {
...
\\task to be executed
\\Check the table for records to be processed
let obj = checkTablesForData();
\\Send third party request with object data. ie - id's
obj.map( id => {
\\call request routine
requestRoutine(id)
})
\\Run final process
runNecessaryUpdate(id)
}
task.js
checkTablesForData(){
...
}
requestRoutine(id){
...
}
runNecessaryUpdate(id){
...
}
module.exports = { runNecessaryUpdate, checkTablesForData, requestRoutine }
Code for api setup
app.js
const express = require('express')
const path = require('path')
const app = express() //, api = express();
const cors = require('cors');
const bodyParser = require('body-parser');
app.get('/', function(req, res){
res.redirect('./api')
})
const api = require('./routes/api');
app.use('/api', api)
module.exports = app
server.js
const app = require('./app');
const port = process.env.PORT || 3000;
app.listen(port, 'localhost', () => {
console.log(`Server is running on port ${port}`);
});
api.js
const express = require('express');
const router = express.Router();
//Controller Modules
const controller = require('../controllers/homeController');
//Routes
router.get('/request/:id', controller.post)
module.exports = router;
controller.js
//Send request to 3rd party api
export.post = function(req, res){
const options = {
....
}
return request(options)
.then( response => {
...
}
.catch( error => {
\\error routine
}
}
Advice is very much needed.
Thanks!

Unable to load data from MongoDB Atlas from heroku app after succesful deployment

I am a beginner to MERN stack development.I have deployed my nodejs app without any error on heroku.But the app does not load the data from mongodb atlas database.The app connects to database and displays the data without any problem when run locally.Any ideas on how to fix this?
I have already added environment variable on heroku and whitelisted all ip addressed on atlas.But still the app does not load data from the database
server.js
const express = require('express'); //nodejs framework for creating web apps
const cors = require('cors');
const mongoose = require('mongoose');
const path = require('path');
require('dotenv').config(); //for setting environment variables on server
const app = express(); //creating the app
//Serve static assets if 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'));
});
}
////////////////////////////////////////
const port = process.env.PORT || 5000;
app.use(cors()); //for cross origin resource sharing ie.cross domain requests
app.use(express.json()); //for handling json data
const uri = process.env.ATLAS_URI;
mongoose.connect(uri,{ useNewUrlParser: true, useCreateIndex: true ,useUnifiedTopology: true });
const connection = mongoose.connection;
connection.once('open',() => {
console.log('Database connection established successfully');
})
const exercisesRouter = require('./routes/exercises');
const usersRouter = require('./routes/users');
//executes the files in the second argument when user enters the url 'rooturl/firstargument'
app.use('/exercises',exercisesRouter);
app.use('/users',usersRouter);
app.listen(port,() => {
console.log(`Server is running on port:${port}`);
});
http://justworkout.herokuapp.com/
This is the app url
The list of exercises should load from the database but nothing is loaded as you can see
I had the same problem. The solution for me it was to go to my client folder and change all my fetch methods. For fetching data I'm using axios. I was sending request to localhost:5000 and then /api/etc. The request was something like this:
axios.get("http://localhost:5000/apps/blog").then()
To make it work on heroku I needed to remove the prefix of localhost and leave just the api path.
axios.get("/apps/blog").then()
Changing this sort my problem.

How can I detect if my express (4.0) node.js app is using a specific piece middleware?

For the purposes of Unit testing I'd like to be able to work out if some middleware is in use.
For example
app.js
var express = require('express');
var morgan = require('morgan');
module.exports = function(options) {
var app = express();
if (options.logRequests) {
app.use(morgan('dev'));
}
return app;
}
app.test.js (run via mocha)
describe('app', function(){
it('should log requests when initialized with the `log requests` option', function() {
var app = require('./app)({ logRequests: true });
// Something to establish whether or not morgan is in use
})
})
I believe middleware is pushed to the seemingly undocumented express "stack", which can be accessed via the app._router.stack array, but this looks like a pretty horrible way to get to what I'm after.
Is anyone aware of a better way to this my assertion?
Thanks

Resources