I am new to node and express js facing issue to access .env variables
webapp.js:
const express = require("express");
const app = express();
require('dotenv').config();
app.listen(process.env.app_port, () => {
//console.log("server running....", process.env);
console.log("server running....", process.env.app_port);
});
.env file:
node_env : development
app_port : 5000
db_port : 3306
host : localhost
user : root
password :
database : job_portal
connectionLimit : 10
package.json
{
"name": "webservices",
"version": "1.0.0",
"main": "webapp.js",
"scripts": {
"start": "nodemon webapp.js",
"dev": "nodemon webapp.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"bcrypt": "^5.0.0",
"express": "^4.17.1",
"mysql": "^2.18.1"
},
"devDependencies": {
"cross-env": "^7.0.2",
"dotenv": "^8.2.0",
"nodemon": "^2.0.4"
},
"description": ""
}
I am trying to access variable in webapp.js from .env file but it return undefined how to fix this?
change your.env file to
node_env = development
app_port = 5000
db_port = 3306
host = localhost
user = root
#YOU VARIABLES SHOULD CAPITALISE AS THIS IS THE CONVENTION
NODE_ENV=development
APP_PORT=5000
DB_PORT=3306
HOST=localhost
USER=root
Related
I'm trying to connect my server (based on node.js) with db from pgAdmin.<>
However I keep getting '${PORT}', instead of PORT's value in env file :
pgAdmin part:
index.js file:
require('dotenv').config()
const express = require ('express')
const sequelize = require('./db')
const PORT = process.env.PORT || 5000
const app = express()
const start = async () => {
try {
await sequelize.authenticate()
await sequelize.sync()
app.listen(PORT,()=>console.log('Server started on port ${PORT}'))
} catch (e) {
console.log(e)
}
}
start()
db.js:
const {Sequelize} = require('sequelize')
module.exports = new Sequelize(
process.env.DB_NAME,
process.env.DB_USER,
process.env.DB_PASSWORD,
{
dialect:'postgres',
host: process.env.DB_HOST,
port: process.env.DB_PORT
}
)
.env file:
PORT=7000
DB_NAME=postgres
DB_USER=postgres
DB_PASSWORD='Ondj8_oP1sw'
DB_HOST=localhost
DB_PORT=5432
package.json:
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "nodemon index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^16.0.1",
"express": "^4.18.1",
"pg": "^8.8.0",
"pg-hstore": "^2.3.4",
"sequelize": "^6.21.4"
},
"devDependencies": {
"nodemon": "^2.0.19"
}
}
The actual connection should be fine, yet your console.log should look like console.log(`Server started on port ${PORT}`), use back ticks `` if you want to console.log a variable.
I deployed react app successfully to Heroku but when click app link in terminal new window displays "Application Error" and error message in terminal states the following:
"import { Server } from 'socket.io'; SyntaxError: The requested module 'socket.io' does not provide an export named 'Server'
Server.js
import http, { request } from 'http';
import { Server } from 'socket.io';
const httpServer = http.Server(app);
const io = new Server(httpServer, { cors: { origin: '*' } });
const users = [];
package.json
{
"name": "app",
"type": "module",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"heroku-postbuild": "cd frontend && npm install && npm run build",
"start": "nodemon --watch backend --exec node --experimental-modules backend/server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"dotenv": "^16.0.1",
"engine.io-client": "^6.2.2",
"express": "^4.18.1",
"express-async-handler": "^1.2.0",
"jsonwebtoken": "^8.5.1",
"mailgun-js": "^0.22.0",
"mongoose": "^6.4.0",
"multer": "^1.4.5-lts.1",
"socket.io": "^4.5.1",
"socket.io-client": "^4.5.1"
},
"devDependencies": {
"nodemon": "^2.0.18"
},
"engines": {
"node": "12.4.0",
"npm": "6.9.0"
}
}
I'm encountering the following error while trying to launch my docker container:
Error:
server_1 | /usr/src/app/node_modules/whatwg-url/lib/encoding.js:2
server_1 | const utf8Encoder = new TextEncoder();
server_1 | ^
server_1 |
server_1 | ReferenceError: TextEncoder is not defined
Dockerfile:
FROM --platform=linux/amd64 node:current-alpine
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
CMD ["npm", "run", "prod"]
docker-compose.yml:
version: '3'
services:
server:
build:
context: ./server
ports:
- "3008:3002"
environment:
API_PORT: "3002"
DB_HOST: "192.168.1.211"
DB_PORT: "27018"
DB_NAME: "tutorialitems"
restart: always
index.js file:
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(bodyParser({ limit: '50mb' }));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//DB
const db = require('./models');
const dbConfig = require('./config/db.config');
try {
db.mongoose.connect(`mongodb://${dbConfig.HOST}:${dbConfig.PORT}/${dbConfig.DB}`, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
console.log('DB Connected!');
} catch (error) {
console.log('Cannot connect to DB...', error);
process.exit();
}
//Routes
require('./routes/crud.routes')(app);
app.get('/', (req, res) => {
res.json("Server is Running")
});
app.listen(process.env.API_PORT, () => {
console.log(`Server is listening on port ${process.env.API_PORT}`)
});
What I tried (but unsuccessfully):
I updated the following file: node_modules > whatwg-url > lib > encoding.js from
Initial:
"use strict";
const utf8Encoder = new TextEncoder();
const utf8Decoder = new TextDecoder("utf-8", { ignoreBOM: true });
to Updated:
const util = require("util");
const utf8Decoder = new util.TextEncoder("utf-8", { ignoreBOM: true });
package.json:
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "nodemon index.js",
"prod": "node index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.17.2",
"mongoose": "^6.1.5",
"nodemon": "^2.0.15"
}
}
But when I run my docker-compose, I still have the same error.
Anyone has an idea?
Thks
Mongoose v6.1.5 is working with Node 17.3.0.
Package.json
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "nodemon index.js",
"prod": "node index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.17.2",
"mongoose": "^6.1.5",
"nodemon": "^2.0.15"
}
}
After updating my package.json with the Mongoose 6.1.5 version, and my Dockerfile as following:
FROM --platform=linux/amd64 node:17.3.0
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
CMD ["npm", "run", "prod"]
I run the following docker-compose commands:
docker-compose pull
docker-compose build
docker-compose up
And now it's working. It seems that docker-compose up was still using the previously build version... thus, it was not working...
package.json:
"mongoose": "^6.2.7"
DockerFile:
FROM node:17-slim
I was getting the same error, when I set the versions as above (node:16-slim to 17-slim), my problem went away. Thanks..
I'm trying to use nodemon on my macbook and whenever i run
nodemon <script.js>
It gives me this error:
address already in use <PORT NUMBER HERE>
Even if i'm running the script for the very first time. I've tried
npx kill-port <port>
But it doesn't work: it shows that a process was killed but when i try to run nodemon again, i get the same error.
Here's my package.json:
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "nodemon server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"dotenv": "^10.0.0",
"express": "^4.17.1",
"nodemon": "^2.0.7"
}
}
My server.js:
const express = require("express");
const dotenv = require("dotenv");
const app = express();
dotenv.config();
const PORT = process.env.PORT;
app.get("/getRestaurants", (req, res) => {
console.log("Get All Restaurants");
});
app.listen(PORT, () => {
console.log(`Server is up on port ${PORT}`);
});
And my .env:
PORT = 4000;
What could be causing this? I'm on a M1 MBA with bigsur.
I have deployed my site to google cloud platform and the react(static) part is working fine, but anytime I go to /api/mail/send to use nodemailer I either get a 404 error saying it cant be found or with some configurations in the yaml file I just a 500 error.. below is my yaml, package.json and server.js files
App.yaml
runtime: nodejs12
env: standard
basic_scaling:
max_instances: 5
idle_timeout: 5m
handlers:
- url: /api/.*
secure: always
script: auto
- url: /
static_files: client/build/index.html
upload: client/build/index.html
secure: always
- url: /
static_dir: client/build
secure: always
Package.json
{
"name": "mern",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"start": "node server.js",
"dev": "concurrently \"nodemon --ignore 'client/*'\" \"npm run client\"",
"client": "cd client && npm run start",
"install": "cd client && npm install",
"build": "cd client && npm run build"
},
"author": "",
"license": "ISC",
"devDependencies": {
"autoprefixer": "^9.8.6",
"concurrently": "^5.3.0",
"husky": "^4.2.5",
"postcss-cli": "^7.1.1",
"tailwindcss": "^1.6.2"
},
"dependencies": {
"if-env": "^1.0.4",
"axios": "^0.19.2",
"body-parser": "^1.19.0",
"classnames": "^2.2.6",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"express-session": "^1.17.1",
"morgan": "^1.10.0",
"nodemailer": "^6.4.11"
}
}
server.js
require('dotenv').config()
const express = require("express");
const morgan = require('morgan');
const routes = require("./routes");
const path = require('path');
const app = express();
const PORT = process.env.PORT || 3001;
// Define middleware here
app.use(morgan('dev'));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// Add routes, both API and view
app.use(routes);
// Serve up static assets (usually on heroku)
app.use(express.static("client/build"));
// Start the API server
app.listen(PORT, function() {
console.log(`🌎 ==> API Server now listening on PORT ${PORT}!`);
});
Thanks