Well, i have 3 types of environments (i.e development,test,production) am using nodejs with express. My problem is this my either development and production scripts don't run because they can't access .env variables i have searched online but i can't find something helpful. This is what i did i created .env file and put my variables in. i tried using export command i.e export key=value. please help
I created a .env file and added either of development database url and production database url, but when i run either of environment it doesn't work. i also tried using export command export key=value. but it works for a while and then it fails again.
//my config
require('dotenv').config();
module.exports ={
development :{
use_env_variable: process.env.DEVELOPMENT_URL,
dialect: 'postgres'
},
production :{
use_env_variable:process.env.PRODUCTION_URL,
dialect: 'postgres',
}
}
//my package.json scripts
{
"name": "report_deck",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "export NODE_ENV=production && sequelize db:migrate && node ./build/index.js",
"dev": "nodemon --exec babel-node ./api/index.js",
"test": "export NODE_ENV=test && sequelize db:migrate:undo:all && sequelize db:migrate && nyc --require #babel/register mocha ./api/test/test.js --timeout 20000 --exit",
"build": "rm -rf ./build && babel -d ./build ./api -s",
"generate-lcov": "nyc report --reporter=text-lcov > lcov.info",
"coveralls-coverage": "coveralls < lcov.info",
"codeclimate-coverage": "codeclimate-test-reporter < lcov.info",
"coverage": "nyc npm test && npm run generate-lcov && npm run coveralls-coverage && npm run codeclimate-coverage"
},
}
//.env
DEVELOPMENT_URL=postgres://example1:pass#example:5432/dbname
PRODUCTION_URL=postgres://example2:pass#example:5432/dbname
//my index.js
import express from 'express';
import bodyParser from 'body-parser';
import classRoutes from './server/routes/classRouter';
// all routes
import cors from 'cors';
const app = express();
app.use(bodyParser.json());
app.use(cors());
//use all routes
app.use(bodyParser.urlencoded({ extended: false }));
const port = process.env.PORT || 8003;
app.get('*', (req, res) => res.status(200).send({
message: "Entrance"
}));
app.listen(port, () => {
console.log("Entrance done, We are running at port " + port);
});
export default app;
Expectations:
It should log "entrance done we are running on port 8003" for (npm run dev)
It should log "entrance done we are running on port 5000" for(heroku local web)
Actual:
throw new TypeError('Parameter "url" must be a string, not ' + typeof url);
You should add -r dotenv/config to your starting script to preload dotenv =>
"start": "export NODE_ENV=production && sequelize db:migrate && node -r dotenv/config ./build/index.js",
Check docs
Related
This is my Setting in package.json
"scripts": {
"start": "node backend/server.js",
"dev": "set NODE_ENV=DEVELOPMENT& nodemon backend/server",
"prod": "set NODE_ENV=PRODUCTION& nodemon backend/server"
},
This is my server.js looks like
const app = require('./app')
const dotenv = require('dotenv')
//dotenv path
dotenv.config({ path: 'backend/config/config.env' })
app.listen(process.env.PORT, () => {
console.log(
`Server started on PORT: ${process.env.PORT}. in ${process.env.NODE_ENV}`
)
})
My config.env looks like
PORT = 4000
NODE_ENV = DEVELOPMENT
I Use nodemon,... and i set node_env variable like in package.json
so, when i called
npm run dev : development
npm run prod : production
but when i run npm run prod. i still got server started on PORT 4000 in Development.
Is there any error in my code ?
Try removing the SET command as well as the & If on Linux:
"dev": "NODE_ENV=DEVELOPMENT nodemon backend/server",
"prod": "NODE_ENV=PRODUCTION nodemon backend/server"
Trying to configure proxy in react native with node to run axios calls.
Tried the following code in server/package.json
"proxy": {
"/*": {
"target": "http://localhost:5000/"
}
},
"scripts": {
"start": "node index.js",
"server": "nodemon index.js",
"client": "cd ../client && yarn ios",
"dev": "concurrently \"yarn server\" \"yarn client\""
}
server/authRouter.js
const authRouter = require('express').Router();
authRouter.get('/test', (req, res) => {
res.send('proxy success');
});
module.exports = authRouter;
server/index.js
const express = require('express');
const authRouter = require('./authRouter');
const app = express();
app.use('/auth', authRouter);
const PORT = process.env.PORT || 5000;
app.listen(PORT);
client/app.js
await axios.get('/auth/test');
When I run yarn dev and test an axios call, it logs the following error
LOG [Error: Network Error]
any help would be much appreciated.
Try calling the proxy directly in axios
http://localhost:5000/auth/test
I'm not sure why it doesn't work that way, even i had a problem in the past.
I want to use process.env
-this is db.js-
import * as dotenv from "dotenv";
import mongoose from "mongoose";
dotenv.config();
const { DB_URL } = process.env.PRODUCTION ? process.env : "localhost:27017/save-idiot";
const { DB_PROTOCOL } =process.env.PRODUCTION ? process.env : "mongodb"
mongoose.connect(`${DB_PROTOCOL}://${DB_URL}`, {
useNewUrlParser: true,
useFindAndModify: false,
useUnifiedTopology: true
});
const db = mongoose.connection;
const handleOpen = () => console.log("✅ Connected to DB");
const handleError = error => console.log(`❌ Error on DB Connection:${error}`);
db.once("open", handleOpen);
db.on("error", handleError);
-package.json-
"scripts": {
"dev:server": "nodemon --exec babel-node src/init.js -- delay 2",
"dev:assets": "cd src && WEBPACK_ENV=development webpack -w",
"lint": "eslint src/",
"fix": "eslint --fix src/",
"clean": "rm -rf build",
"build:server": "babel src --out-dir build --ignore 'src/assets','src/static','src/webpack.config.js'",
"build:assets": "cd src && WEBPACK_ENV=production webpack",
"copy:static": "cp -R src/static src/views build/",
"build": "npm run clean && npm run lint && npm run build:server && npm run build:assets && npm run copy:static",
"start": "PRODUCTION=true forever start build/init.js"
}
const { DB_URL } = process.env.PRODUCTION ? process.env : "localhost:27017/save-idiot";
const { DB_PROTOCOL } =process.env.PRODUCTION ? process.env : "mongodb"
if I npm run dev:server,
I want to get "localhost:27017/save-idiot" & "mongodb"
and if I npm start,
I want to get process.env
How can I do this?
You could use cross-env package, it is used to set environment variables.
Once you've installed it, you could try like this:
"start": "cross-env PRODUCTION=true forever start build/init.js"
Try use
dotenv.config({ path: '.env' });
For configure many environments you can use envdist
I'm trying to upload an express/node.js app to heroku. The app is deployed succesfully but when I try to access the url I get error: Not Found.
When I run heroku logs --tail I get:
Error: ENOENT: no such file or directory, stat '/client/build/index.html'
so I think I'm doing something wrong with the directories and the statics folder
this is my server.js file:
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const passport = require("passport");
const cors = require("cors");
const path = require("path");
const users = require("./routes/api/users");
const profile = require("./routes/api/profile");
const matches = require("./routes/api/matches");
const app = express();
//body-parser middleware
app.use(bodyParser.urlencoded({ extended: false, limit: "50mb" }));
app.use(bodyParser.json({ limit: "50mb" }));
//db config
const db = require("./config/keys").mongoURI;
//cors
app.use(cors());
//connect to mongoose
mongoose
.connect(db, { useNewUrlParser: true })
.then(() => console.log("MongoDB connected"))
.catch(err => console.log(err));
//Passport middleware
app.use(passport.initialize());
app.use("/images", express.static(path.join(__dirname + "/images")));
//Passport config
require("./config/passport")(passport);
//Use route
app.use("/api/users", users);
app.use("/api/profile", profile);
app.use("/api/matches", matches);
//Serve static assets if in production
if (process.env.NODE_ENV === "production") {
app.enable("trust proxy");
//Set static folder
app.use(express.static(path.join(__dirname, "/../client/build")));
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname + "/../client/build/index.html"));
});
}
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`server running on port ${port}`));
I also include an image of the folders "positions"
I solved this issue by defining build and install command in my package.json. Heroku would look for a build command for production in there.
"scripts": {
"build": "cd client && npm run build",
"install": "cd client && npm install",
"start": "node server",
"server": "nodemon server",
"client": "npm start --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\""
},
I think it should be like this
app.use("/images", express.static(path.join(__dirname, "images")));
Edit: Actually your app is expecting to find a file at /../client/build/index.html but that file does not exist (which is what ENOENT error means). So you either need to create the expected directory structure or else configure your application such that it looks in the correct directory for index.html. That whats i understand now, i hope this would help you.
I also got similar error. For me the problem is I have wrong script for build in package.json file, So build is not creating at all.
Verify you have "heroku-postbuild" script as below in package.json file.
"scripts": {
"start": "node server.js",
"server": "nodemon server.js",
"client": "npm start --prefix client",
"clientinstall": "npm install --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\"",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
},
Here is my project structure:
package.json:
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "nodemon $NODE_DEBUG_OPTION server/boot.js --exec babel-node",
"start": "nodemon server/boot.js --exec babel-node",
"build": "babel server -d dist/server",
"serve": "node dist/server/boot.js"
},
The main file is server/boot.js:
import dotenv from 'dotenv';
import path from 'path';
dotenv.load({path: path.join(__dirname, '.env')});
import _ from 'underscore';
import configs from './config/index';
The server/config/index.js is only a barrel file that imports the other config files:
import app from './app';
import database from './database';
export default Object.assign({}, app, database);
In each of the config files I am not able to access any properties of the process.env object that are defined in the .env file.
Here is one of the config files for reference:
export default {
app: {
host: process.env.HOST || 'localhost',
port: process.env.PORT || 9000,
}
}
Here process.env.HOST is undefined, but the key is present in the .env file.
What I am doing wrong?
process.env object that are defined in the .env file.
Can you please be more specific about the process.env file?
As per https://www.npmjs.com/package/dotenv#rules the file should be in the format:
VAR1=value1
VAR2=value2
and not in
export default {
VAR1: 'value1',
VAR2: 'value2'
}