How to put a Mongo Db URL in dotenv file? - mongodb

I'm trying to add environment file to a node project, and I have put mongo URL in it, now, when I console log it, prints undefined... anyone know where's the problem?
require("dotenv").config();
let MONGO_URL = process.env.MONGO_DB_URL;
console.log("MONGO", process.env.MONGO_DB_URL);
dotenv file
MONGO_DB_URL="mongo URL"
if I print
console.log(require('dotenv'.config()))
CONFIG { parsed: { MONGO_DB_URL: '' } }

check if you had install npm package of dotenv
if yes then it will work else you need to install it
npm i dotenv
in .env file
MONGO_DB_URL= mongodb://localhost:27017
in index file or wherever u want
require("dotenv").config();
let MONGO_URL = process.env.MONGO_DB_URL;

Related

Verify JWT Token error 'secretOrPrivateKey must have a value'

return failure(new Error('secretOrPrivateKey must have a value'));enter image description here
I think your application is not able to read the environnement variables.
I advice you to use the package dotenv : https://github.com/motdotla/dotenv
After installing it you have to import it at the top of your application like this:
require("dotenv").config();
Specify a file .env at the root of your application and add your variables
JWT_SECRET=12bob12ou2b1ob
NODE_ENV=development
After, you can use the variables like you did in your linked image:
const jwtSecret = process.env.JWT_SECRET

ModuleNotFoundError: No module named 'gspread' on python anywhere

What I am trying to achieve.
Run a python script saved On pythonanywhere host from google sheets on a button press.
Check the answer by Dustin Michels
Task of Each File?
app.py: contains code of REST API made using Flask.
runMe.py: contains code for that get values from(google sheet cell A1:A2). And sum both values send sum back to A3.
main.py: contains code for a GET request with an argument as name(runMe.py).filename may change if the user wants to run another file.
I Made an API by using Flask.it works online and offline perfectly but still, if you want to recommend anything related to the app.py.Code Review App.py
from flask import Flask, jsonify
from flask_restful import Api, Resource
import os
app = Flask(__name__)
api = Api(app)
class callApi(Resource):
def get(self, file_name):
my_dir = os.path.dirname(__file__)
file_path = os.path.join(my_dir, file_name)
file = open(file_path)
getvalues = {}
exec(file.read(), getvalues)
return jsonify({'data': getvalues['total']})
api.add_resource(callApi, "/callApi/<string:file_name>")
if __name__ == '__main__':
app.run()
Here is the Code of runMe2.py
import gspread
from oauth2client.service_account import ServiceAccountCredentials
# use creds to create a client to interact with the Google Drive API
scopes =['https://www.googleapis.com/auth/spreadsheets',"https://www.googleapis.com/auth/drive.file","https://www.googleapis.com/auth/drive"]
creds = ServiceAccountCredentials.from_json_keyfile_name('service_account.json', scopes)
client = gspread.authorize(creds)
# Find a workbook by name and open the first sheet
# Make sure you use the right name here.
sheet = client.open("Demosheet").sheet1
# Extract and print all of the values
list_of_hashes = sheet.get_all_records()
print(list_of_hashes)
below is the main.py code
import requests
BASE = 'https://username.pythonanywhere.com/callApi/test.py'
response = requests.get(BASE)
print(response.json())
main.py output
{'data': 54}
Test.py code
a = 20
b = 34
total = a+b
print(total)
PROBLEM IS
if I request runMe2.py at that time I am got this error.
check runMe2.py code above
app.py is hosted on https://www.pythonanywhere.com/
ModuleNotFoundError: No module named 'gspread'
However, I installed gspread on pythonanywhere why using the command. but it's not working.
You either haven't installed the gspread package on your current python environment or it is installed somewhere (e.g. in a diff. virtual env) and your script cant find it.
Try installing the package inside the environment your running your script in using pip3:
pip3 install gspread
You can try something like this on Windows
pip install gspread
or on Mac
pip3 install gspread
If you're running on Docker, or building with a requirements.txt you can try adding this line you your requirements.txt file
gspread==3.7.0
Any other instructions for this package can be found here => https://github.com/burnash/gspread
Download gspread here
Download the tar file: gspread-3.7.0.tar.gz from the above link
Extract file and convert folder in zip then upload it back on server
Open bash console and use command as
$ unzip gspread-3.7.0
$ cd gspread-3.7.0
$ python3.7 setup.py install --user

Loopback 4: Specify environment var in the #model

I am trying to get the mongodb collection name from an environment variable defined in .env. It looks like the model is initialised before the .env is read.
#model({
name: 'MyType',
settings: {
mongodb: process.env.COLLECTION_NAME,
},
})
The process.env.COLLECTION_NAME is, at this point, undefined
Any way to externalised the collection name?
Many thanks for the help.
By default, Node.js does not read from .env.
To read from .env, we need to utilize the dotenv package.
Since models are resolved through the Booter during startup, hence we need to call dotenv.config() before app.boot().
Update index.ts as follows:
// At the top of the file
import dotenv from 'dotenv';
...
// Inside the main function
// dotenv.config() must appear before app.boot()
dotenv.config()
...
app.boot();
app.start();
This would cause dotenv to overwrite process.env with the values in .env where necessary.
Further reading:
https://www.npmjs.com/package/dotenv
How do I setup the dotenv file in Node.js?
in your
src/index.ts
import {ApplicationConfig, MyApplication} from './application';
require('dotenv').config();
export * from './application';
and your .env file in the "root" of your project

How can I run SQL on PostgreSQL RDS from Lambda function in Node.js?

I have this code in Lambda funcion:
sql="SELECT ...";
var pg = require('pg');
var connectionString = 'postgres://...';
var client = new pg.Client(connectionString);
client.connect();
var query = client.query(sql);
query.on('end', function() { client.end(); });
When I run from EC2, it works fine. When I run from Lambda I get Error: Cannot find module 'pg'
I am a super noob in Node JS, but I really wanted to try AWS Lambda. Here are the steps I took. I used a Ubuntu 14.04.
sudo apt-get update
sudo apt-get install nodejs
sudo apt-get install npm
sudo ln -s /usr/bin/nodejs /usr/bin/node
mkdir the_function && cd the_function
mkdir node_modules
npm install pg
******Now create a file index.js and paste the content of your funcion.
console.log('Loading S2 Function');
var pg = require("pg");
exports.handler = function(event, context) {
var conn = "pg://user:password#host:5432/bd_name";
var client = new pg.Client(conn);
client.connect();
var query = client.query("SELECT * FROM BLA WHERE ID = 1");
query.on("row", function (row, result) {
result.addRow(row);
});
query.on("end", function (result) {
var jsonString = JSON.stringify(result.rows);
var jsonObj = JSON.parse(jsonString);
console.log(jsonString);
client.end();
context.succeed(jsonObj);
});
};
******Now zip the contents of the_function folder (not the_function folder itself)
You can check the official sample from this AWS link: http://docs.aws.amazon.com/lambda/latest/dg/walkthrough-s3-events-adminuser-create-test-function-create-function.html
You can import easily only predifined libs to your lambda. For example You can use just boto3 and core for python, for java You can use just core. http://docs.aws.amazon.com/lambda/latest/dg/current-supported-versions.html
You cannot import any additional libs in simple way.
You can try to use "hard way".
In this case You should save all necessary libraries to s3(or other place which You can access from lambda) and then copy to lambda environment (/tmp) and import it with the help of reflection.
Error: Cannot find module 'pg'
In my case I was just uploading index.js. We need to package 3rd party node modules as well.
create index.js (name may vary based on your handler name)
run npm install package
It is better you create package.json will all dependencies you need and run mpn install
Confirm node_modules folder is created in same directory.
Zip these contents (index.js and node_modules folder) and upload the zip.
You can upload directly or use S3.
For more details read their offcial doc - Creating a Deployment Package (Node.js)
Now I get: Unable to import module 'index': Error . Is my function must be called index.js
In my case I was zipping the entire directory instead of it's contents. So you need to really do -
zip -r deploymentpkg.zip ./*
instead of
zip -r deploymentpkg.zip folder

sails.js Is it possible to set process.env variables from application?

I am trying to use npm module fb to use facebook api. The config file is located in the module and here is the snapshot of the same
var config = { };
// should end in /
config.rootUrl = process.env.ROOT_URL || 'http://localhost:3000/';
config.facebook = {
appId: process.env.FACEBOOK_APPID || '130243393813697',
appSecret: process.env.FACEBOOK_APPSECRET || 'c82696768ae4ad8b63db874cb64eb558',
appNamespace: process.env.FACEBOOK_APPNAMESPACE || 'nodescrumptious',
redirectUri: process.env.FACEBOOK_REDIRECTURI || config.rootUrl + 'login/callback'
};
module.exports = config;
I don't wish to change the config file of the module since node_modules folder is kept in the gitignore list. For configuring the module to use my app's appId and appSecret, I need to set the process.env variables FACEBOOK_APPID and FACEBOOK_APPSECRET
I understand that it can be done while calling the sails lift but is it by any means possible to set these values inside the app so that I only have to call
sails lift
without any of those variables and those should be set automatically ? Or what is the best way to achieve what I am trying to do here ?
You should set the environment-variables outside of your App.
Instead of sails lift you could also use node app.js. With that you can define environment-variables for your node-application with:
$> FOO='bar' node app.js
In your case:
$> FACEBOOK_APPID='232322a22' FACEBOOK_APPSECRET='mysecrete' node app.js
If you want to set this vars in your app (I wouldn't suggest that!) you could set them before including your npm-module. For example in your config/bootstrap.js:
module.exports.bootstrap = function(cb) {
process.env.FACEBOOK_APPID = "myvar";
process.env.FACEBOOK_APPSECRET = "mysecrete";
sails.facebook = require("yourmodule");
cb();
};
Here is a good link for setting environment variables when "Production", "Staging" and "Development" in Sails feels fragmented.
Here is a quick video tutorial which simply explains how to create environment variables in node.js
Step1:
Install the package dotenv as dependency
$ npm install dotenv --save
Step2:
Then require dotenv in app.js and load the .env file
var dotenv = require('dotenv');
dotenv.load();
Step3:
Create a .env file in the root folder (ie. at the same document level as app.js file)
Step4:
Add your environment variables
S3_KEY=enfiownqefniqofewqofnieqwvewlk
S3_SECRET=123456789
Now you can access those environment variables anywhere in the app (probably in some config/ files):
return {
key: process.env.S3_KEY,
secret: process.env.S3_SECRET,
region: 's3-eu-west-1',
bucket: 'myBucket',
s3params: {
ACL: 'public-read'
}
}
Credit goes to Noah Bass for providing this tutorial.