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.
Related
server.js
import express from 'express';
import { routes } from './routes';
import { db } from './db';
const app = express();
app.use(express.json());
routes.forEach(route => {
app[route.method]('/api' + route.path, route.handler);
});
const start = async () => {
await db.connect('mongodb://localhost:27017');
await app.listen(8080);
console.log('Server is listening on port 8080');
};
start();
one route deleteIngredientRoute.js
import { deleteIngredient, getIngredients } from '../db';
export const deleteIngredientsRoute = {
path: '/meals/:name',
method: 'DELETE',
handler: async (req, res) => {
const { name } = req.params;
await deleteIngredient(name);
const updatedIngredients = await getIngredients();
res.status(200).json(updatedIngredients);
},
};
package.json
{
"name": "fsa-back-end-template",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "npx nodemon --exec 'npx babel-node src/server.js'"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"nodemon": "^2.0.20"
},
"dependencies": {
"#babel/cli": "^7.19.3",
"#babel/core": "^7.20.2",
"#babel/node": "^7.20.2",
"#babel/preset-env": "^7.20.2",
"#babel/register": "^7.18.9",
"express": "4.17.1",
"mongodb": "4.1.0"
}
}
Error
app[route.method]('/api' + route.path, route.handler);
^
TypeError: app[route.method] is not a function
Also sometimes i get this error
''npx' is not recognized as an internal or external command,
operable program or batch file.
[nodemon] app crashed - waiting for file changes before starting...
I am using NVM i added to environment Path variables
I'm trying to upload a node app to Vercel and use as API but I'm getting an This Serverless Function has crashed. error message. The fact that I can run it with no problems in localhost, and the fact that the build log doesn't throw an error, I can't seems to find the problem.
Here is a full Screenshot:
vercel app
And here is my index.js:
const express = require(`express`);
var cors = require('cors')
const app = express();
app.use(cors())
const bodyParser = require('body-parser')
const mongoose = require("mongoose")
require("dotenv").config();
const config = require('config');
const dbConfig = config.get("MT.dbConfig.dbName")
mongoose.connect(dbConfig, {
}).then(() => {
console.log('Database connected.')
}).catch((err)=> console.log('Something went wrong with the database : ' + err))
mongoose.Promise = global.Promise;
app.use(bodyParser.json())
app.use('/', require('./api/v1/api'))
app.use((err, req, res, next) =>{
res.status(422).send({
error: err._message
})
})
const PORT = 5001;
app.listen(PORT, () => console.log("API is running."))
And here is my package.json:
{
"name": "hidden",
"version": "1.0.0",
"description": "",
"main": "index.js",
"engines": {
"node": "14.x"
},
"scripts": {
"start": "vercel dev",
"deploy": "vercel deploy --prod"
},
"author": "hidden",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"config": "^3.3.6",
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.17.1",
"mongoose": "^6.0.13",
"vercel": "^23.1.2"
},
"devDependencies": {
"nodemon": "^2.0.15"
}
}
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 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
I'm trying to follow a tutorial for starting up my first NodeJS app, but I don't understand why I am getting this error. I'm attempting to connect a MongoDB database with the app, and obviously had to modify my Start.js file in order to do that... but the error says I'm missing that file completely. Here's my Start.js:
require('dotenv').config();
const mongoose = require('mongoose');
mongoose.connect(process.env.DATABASE, { useMongoClient: true });
mongoose.Promise = global.Promise;
mongoose.connection
.on('connected', () => {
console.log(`Mongoose connection open on ${process.env.DATABASE}`);
})
.on('error', (err) => {
console.log(`Connection error: ${err.message}`);
});
const app = require('./app');
const server = app.listen(3000, () => {
console.log(`Express is running on port ${server.address().port}`);
});
I was told to create a .env file to place in the project folder as well, could this have something to do with it? Maybe the address to the database is incorrect? Any assistance would be greatly appreciated.
EDIT: Here's my package.json file
{
"name": "demo-node-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"watch": "nodemon ./start.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"express-validator": "^6.3.0",
"mongoose": "^5.8.3",
"pug": "^2.0.4"
},
"devDependencies": {
"nodemon": "^2.0.2"
}
}