How to publish a API project with heroku? - node.js

I try to publish an API application with Heroku but I am getting an error. What could be the reason? I might be doing something missing. Can you show me what I'm missing?
heroku logs --tail Result
Application index
edit:

I dont have your code snippet so i'm just giving my example here for local development and heroku setup both
In local development
install dotenv npm package
create .env file in root directory and set MONGOURI='Your mongo string here'
then you can import dotenv package in root as shown in below example and use variable as process.env.MONGOURI
On Heroku
there are multiple ways you can do same thing as above which are listed here in config vars. More specifically i'll suggest you to do this way from heroku frontend
require('dotenv').config(); // <-- install `dotenv` package
const MongoClient = require('mongodb').MongoClient;
const mongoUrl = process.env.MONGOURI;
// Connect to the db
MongoClient.connect(mongoUrl, function (err, db) {
if(err) throw err;
db.open(function(err, mongoClient) {
console.log("mongo connected");
});
db.close();
});
I had created a node with mongo boilerplate project to get me started you can check if you want node-auth-mongo

Related

Need Advise : Index.js in not able to find the gitlab path of my postman collection while running a job in gitlab CI/CD

I have uploaded a postman collection, modules, package.json and index.js on GitLab. While executing the index.js using the node index.js command it is failing with the error: can not find module 'PostmanCollection/MPDC.postman_collection.json'. I have provided the GitLab path of the collection in the index.js but still, it ends up failing. This works fine when I am using the local path.
Can anyone please advise me on how to fix this issue?
Here is how my index.js looks:
const newman = require('newman');
newman.run({
collection: require('PostmanCollection/MPDC.postman_collection.json'),
reporters: 'cli',
}, function (err){
if (err) {throw err;}
console.log('collection run complete');
});

deploy module to remote server that is running node.js

I'm working on my app.js in node.js
-- trying to deploy server-side script.
Many fine node.js modules need a require('something');
I use NPM locally, which works for require, as modules are nicely visible in the local node_modules folder structure. but now I'm ready to upload or bundle to a host. I can't run npm on this hosted server.
const Hapi = require('hapi');
will result in
Error: Cannot find module 'hapi'
because I don't know how to copy/install/bundle/ftp files to my host.
Hapi is just an example. Most anything that has a require will need something on the host.
I used webpack to create a server side bundle.js but just sticking bundle.js under /node_modules doesn't do anything.
Most modules have a complex folder structure underneath --- I'm trying to avoid copying a ton of folders and files under /node_modules. Ideally, I want to combine the modules into a bundle.js and have those modules visible to app.js
but I am open to other ideas.
I have not yet tried using webpack to bundle app.js TOGETHER with the various modules. Have you had luck with that approach?
thanks.
I've tried to upload hapi files a folder-ful at a time, reaching a new require('something') error at every step.
'use strict';
const Hapi = require('hapi'); // <-- how can I deploy hapi on my node.js server?
// Create a server with a host and port
const server=Hapi.server({
host:'localhost',
port:8000
});
// Add the route
server.route({
method:'GET',
path:'/hello',
handler:function(request,h) {
return'hello world';
}
});
// Start the server
async function start() {
try {
await server.start();
}
catch (err) {
console.log(err);
process.exit(1);
}
console.log('Server running at:', server.info.uri);
};
start();
one approach that worked: using webpack to bundle the back end js.
thanks to
https://medium.com/code-oil/webpack-javascript-bundling-for-both-front-end-and-back-
end-b95f1b429810
the aha moment... run webpack to create bundle-back.js then
tie bundle-back.js to my node server
**You start your backend server with ‘bundle-back.js’ using:
node bundle-back.js
In other words, include app.js in the bundle with the modules.

How to connect Mongo DB in a webpack dev server

I would like to connect to Mongo DB using a webpack dev server. While the connection using the node mongodb driver and configuring in server.js is direct and straight forward, I am thinking of a way to do the same using webpack dev server in development (mainly for the hot loading advantage).
I understand that there is a way of achieving the same using a webpack middleware, but is there another easier and better way of doing it.
webpack dev-server is generally a simple Express or similar node.js server. It's essentially exactly the same as writing is on an express.js server.
npm install mongoose mongodb --save-dev
const mongoose = require('mongoose'); // Replace with import as desired
const mongoConnectString = 'mongodb://localhost/database-name-here';
mongoose.connect(mongoConnectString, (err) => {
if (err) {
console.log('Err, could not connect to the database.');
}
});
Replace the mongoConnectString as needed for developing or using databases that aren't local to your machine.

connecting node js to postgresql on heroku

I have deployed my app on heroku and was able to make a connection to the database from pg:psql in my terminal by copying and pasting the code provided by heroku. Now i want to directly connect my node app to postgres on heroku but no success. I followed the instruction on heroku on how to connect nodejs to postgres here.. https://devcenter.heroku.com/articles/heroku-postgresql#connecting-in-node-js but i can't seem to get it to work. I simply installed pg module and pasted the block of code provided by heroku inside my get request in my server.js file.
app.use(express.static('public'));
app.use(bodyParser.json());
app.get('/food', function(req, res) {
pg.defaults.ssl = true;
pg.connect(process.env.DATABASE_URL, function(err, client) {
if (err) throw err;
console.log('Connected to postgres! Getting schemas...');
client.query('SELECT table_schema,table_name FROM information_schema.tables;').on('row', function(row) {
console.log(JSON.stringify(row));
});
});
});
http.listen(process.env.PORT || 3000, function(){
console.log('listening to port 3000!');
});
the error i get from heroku logs is..
/appserver.js:53
if (err) throw err;
Error: connect ECONNREFUSED 127.0.0.0.1:5432
after searching for that error message, i get some people suggesting on fixing or changing the DATABASE_URL. How and where do i change it? I'm lost. I would really appreciated if i can get some help to fix it.
The pg connection is using the database url in your environment:
pg.connect(process.env.DATABASE_URL, function(err, client) {}
Because the DATABASE_URL env variable is not set, it defaults to localhost 127.0.0.0.1:5432. You can set DATABASE_URL in your bashrc or bash_profile. You can name it more specifically PROJECTNAME_DATABASE_URL if you have multiple apps. On Heroku, you can set it like this:
$ heroku config:set DATABASE_URL=postgres://user:password#host:port/database

Heroku + mongoose connection error: no primary server found in set

I have a mongodb replica set on mongolab.
I'm using nodejs + mongoose. When I'm trying to connect from my local machine everything goes ok.
But after deployment to heroku something wrong happens and mongoose got strange error:
[Error: no primary server found in set]
Here some code (server.js):
async.series([
function(callback){
console.log('DB Connection: ' + siteConf.mongo_url);
mongoose.connect(siteConf.mongo_url, siteConf.mongo_options, callback);
},
function(callback){
http.createServer(app).listen(siteConf.port, callback);
}
],
function(err, results){
if (err) {
console.log(err);
}
console.log('Running in ' + (process.env.NODE_ENV || 'development') + ' mode # ' + siteConf.uri);
}
);
This url I'm using as connection string:
mongodb://username:password#someid-a0.mongolab.com:39897/pm_prod,mongodb://someid-a1.mongolab.com:39897
The main thing I can't understand is: what is the differences between my maching and heroku cloud hosting.
I already tried to remove node_modules and npm install them to be sure that I have same versions as on heroku. (Because heroku do this on each deploy).
Thanks, and sorry for my bad english
This may be a URI problem. The format for DB URIs is:
mongodb://<user>:<pass>#host:port,host:port,...,host:port/db_name
That means that
mongodb://username:password#someid-a0.mongolab.com:39897/pm_prod,mongodb://someid-a1.mongolab.com:39897
should be:
mongodb://username:password#someid-a0.mongolab.com:39897,someid-a1.mongolab.com:39897/pm_prod
It's also worth noting for others: If you are using Heroku's MongoLab add-on, your URI is available as an environment variable at process.env.MONGOLAB_URI, so you don't have to place the URI in your code.
This could also be related to a running question about connectivity between Heroku and Mongo. See https://github.com/jcottr/temps-mort, which references two tickets for the Node Mongo driver:
https://jira.mongodb.org/browse/NODE-4
https://jira.mongodb.org/browse/NODE-5

Resources