Javascript says that my variables which are in .env are undefined. I've installed dotenv but it doesn't work.
My index.js
const express = require("express");
const mongoose = require("mongoose");
const app = express();
const router = express.Router();
const port = process.env.PORT || 5000;
const dotenv = require("dotenv");
const userRoute = require('./routes/user');
const authRoute = require('./routes/auth');
mongoose.set('strictQuery', false);
dotenv.config();
mongoose
.connect(
process.env.MONGODB_URL
)
.then(() => console.log("Database is working"))
.catch((err) => {
console.log(err)
});
app.use(express.json());
app.use('', authRoute);
app.listen(process.env.PORT, function () {
console.log('Server is up on port ' + process.env.PORT)
})
My auth.js
const router = require('express').Router();
const User = require('../models/user');
const Crypto = require('crypto-js');
const { response } = require('express');
const secretKey = process.env.SECRET_KEY;
// Create a registration
console.log(secretKey);
router.post('/rejestracja', async (req, res)=>{
const nowyUser = new User({
email: req.body.email,
password: Crypto.AES.encrypt(req.body.password, process.env.SECRET_KEY).toString(),
firstName: req.body.firstName,
surname: req.body.surname,
username: req.body.username,
});
try{
const newedUser = await nowyUser.save();
res.status(201).json(newedUser);
}
catch(err){res.status(500).json(err)};
})
// Create a login
router.post('/login', async (req, res) => {
try{
const user = await User.findOne({email: req.body.email});
if (!user) {
return res.status(401).json("i/lub hasło jest nieprawidłowy");
}
const securedPass = Crypto.AES.decrypt( user.password, "a");
const password = securedPass.toString(Crypto.enc.Utf8);
console.log(password);
if (password !== req.body.password) {
res.status(401).json("Email i/lub hasło jest nieprawidłowy");
}else {
res.status(200).json(user);
}
}
catch(err) {
res.status(500).json({message: err.message});
}
});
module.exports = router
And my .env
MONGODB_URL = mongodb+srv://someInterestingWords
PORT = 5500
SEC_KEY = a
Everything works when these variables are in my code, not in .env.
I've tried to delete dotenv and add it again but id doesn't change anything.
process.env.something works in index.js but it doesn't in other files
My project file structure
At the moment you doing require, Node.JS executing specified file (or importing lib).
Now let's look at first lines of Your code:
const dotenv = require("dotenv");
const userRoute = require('./routes/user');
const authRoute = require('./routes/auth');
mongoose.set('strictQuery', false);
dotenv.config();
You may notice: first you doing require on ./routes/user and ./routes/auth, then you doing dotenv.config().
You need to do dotenv.config() Before using process.env, so try next:
const express = require("express");
const mongoose = require("mongoose");
const app = express();
const router = express.Router();
/*
Doing `config` just after `require`.
Also, in most cases, You don't need dotenv after using this once,
so no need to store `dotenv` constant.
*/
require("dotenv").config();
const port = process.env.PORT || 5000;
const userRoute = require('./routes/user');
const authRoute = require('./routes/auth');
// other lines...
Also notice, if .env file locates not in __dirname (directory, where launches main file), you need to specify it's location:
require('dotenv').config({path: '../configs/.env'});
or using path:
const path = require('path');
require('dotenv').config({path: path.join(__dirname, '../configs/.env')});
Related
By the Postman cant send POST request with data to postgresgl
https://i.stack.imgur.com/lwGnB.jpg
Terminal sends an error:
https://i.stack.imgur.com/cTJIy.jpg
Fow now I can't send post and get requests. Can't understand why the server is not receiving any data
BookController.js:
enter code here
const uuid = require('uuid')
const path = require('path');
const {Book} = require('../models/models')
const ApiError = require('../error/ApiError');
class BookController {
async create(req, res, next) {
try {
const {ISBN, title, publisher, language, num_of_pages, author} = req.body
const {img} = req.files
let fileName = uuid.v4() + ".jpg"
img.mv(path.resolve(__dirname,'..','static', fileName))
const book = await Book.create({ISBN, title, publisher, language, num_of_pages, author, img:fileName})
return res.json(book)
}
catch (e){
next(ApiError.badRequest(e.message))
}
}
async getAll(req, res){
const books = await Book.findAll()
return res.json(books)
}
async getOne(req, res){
}
}
module.exports = new BookController()
BookRouter.js:
const Router = require('express')
const router = new Router()
const bookController = require('../controllers/bookController')
router.post('/', bookController.create)
router.get('/', bookController.getAll)
router.get('/:ISBN', bookController.getOne)
module.exports = router
routes\index.js:
const Router = require('express')
const router = new Router
const bookRouter = require('./bookRouter')
const userRouter = require('./userRouter')
const typeRouter = require('./typeRouter')
router.use('/user', userRouter)
router.use('/type', typeRouter)
router.use('/book',bookRouter)
module.exports = router
index.js:
require('dotenv').config()
const express = require('express')
const sequelize = require('./db')
const models = require('./models/models')
const cors = require('cors')
const fileUpload = require('express-fileupload')
const router = require('./routes/index')
const errorHandler = require('./middleware/ErrorHandlingMiddleware')
const path = require('path')
const PORT = process.env.PORT || 5000
const app = express()
app.use(cors())
app.use(express.json())
app.use(express.static(path.resolve(__dirname, 'static')))
app.use(fileUpload({}))
app.use('/api', router)
app.use(errorHandler)
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()
I am learning MERN development, and trying to create API for adding category by using postman. But getting below error
Cannot POST /api/category/create/62545ea650265cda5b08f10d
I am adding here code and screen shot of postman, I would appreciate for any help!
controller\category.js
const Category = require("../models/category");
//const { errorHandler } = require("../helpers/dbErrorHandler");
exports.create = (req, res) => {
const category = new Category(req.body);
category.save((err, data) => {
if (err) {
return res.status(400).json({
// error: errorHandler(err)
});
}
res.json({ data });
})
}
model\category.js
const mongoose = require('mongoose');
const categorySchema = new mongoose.Schema({
name: {
type: String,
trim: true,
required: true,
maxlength: 32
}
}, { timestamps: true }
);
module.exports = mongoose.model("Category", categorySchema);
routes/category.js
const express = require('express');
const router = express.Router();
const { create } = require('../controllers/category');
const { requireSignin, isAuth, isAdmin } = require('../controllers/auth');
const { userById } = require('../controllers/user');
router.post("/category/create:userId", requireSignin, isAuth, isAdmin, create);
router.param('userId', userById);
module.exports = router;
app.js
// const express = require('express')
// const app = express()
// require('dotenv').config()
// app.get('/',(req, res)=>{
// res.send('hello from node updated');
// })
// const port = process.env.PORT || 8000
// app.listen(port, ()=>{
// console.log(`Servver is running on port ${port}`)
// });
const express = require('express')
// import mongoose
const mongoose = require('mongoose');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const expressValidator = require('express-validator');
// load env variables
const dotenv = require('dotenv');
dotenv.config();
//import routes
const authRoutes = require('./routes/auth');
const userRoutes = require('./routes/user');
const categoryRoutes = require('./routes/category');
//app
const app = express();
//db connection
mongoose.connect(
process.env.DATABASE,
{
useNewUrlParser: true
}
)
.then(() => console.log('DB Connected'));
mongoose.connection.on('error', err => {
console.log(`DB connection error: ${err.message}`)
});
//middlewares
app.use(morgan('dev'))
app.use(bodyParser.json())
app.use(cookieParser());
app.use(expressValidator());
//routes middleware
app.use("/api", authRoutes);
app.use("/api", userRoutes);
app.use("/api", categoryRoutes);
// app.get('/',(req, res)=>{
// res.send('hello from node updated');
// })
const port = process.env.PORT || 8000
app.listen(port, () => {
console.log(`Servver is running on port ${port}`)
});
[1]: https://i.stack.imgur.com/vKqBt.png
just simply use category/create/:userId in your routes
I am facing this issue when trying to run server after create route and use route in app.js file.Please help me to resolve the error i have been stuck here for hours tried a lot of edits but its not working for me.
Here is my courseRoute.js
const express = require('express');
const router = express.Router();
const Course = require('../../models/Course');
const adminAuthMiddleware = require('../../middleware/adminAuthMiddleware');
router.get('/admin/view-course', adminAuthMiddleware, async (req, res) => {
try {
await Course.find((err, docs) => {
if (!err) {
res.render('admin-views/course/view_course', { courses: docs });
} else {
res.send('Error in retrieving Course list :' + err);
}
})
} catch (err) {
res.send(err);
}
});
This is my app.js
require('dotenv').config();
const express = require('express');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const flash = require('connect-flash');
const bodyParser = require('body-parser');
const { check, validationResult } = require('express-validator');
const path = require('path');
require('./db/conn');
const courseRoute = require('./routes/admin routes/courseRoute');
const app = express();
const port = process.env.PORT || 3000;
const static_path = path.join(__dirname, "../public");
app.use(express.static(static_path));
app.use(express.json());
app.use(express.urlencoded({extended: false }));
app.set('view engine', 'ejs');
app.use(courseRoute);
app.listen(port, () => {
console.log(`Server is running at ${port}`);
});
Your courseRoute.js has no exports. In the last line add module.export = route;
I am trying to insert a category and it is not sending its 'name' to the database. On Postman and Robo Mongo I see that I sent '_id', 'createdAt', 'updatedAt' and "_V" all correctly. But the 'name' is not sending. Does anyone know what's going on? Thanks.
app.js
const express = require('express')
const mongoose = require('mongoose')
const morgan = require('morgan')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const expressValidator = require('express-validator')
require('dotenv').config()
//import routes
const authRoutes = require('./routes/auth')
const userRoutes = require('./routes/user')
const categoryRoutes = require('./routes/category')
// app
const app = express()
// db
mongoose.connect(process.env.DATABASE, {
useNewUrlParser: true,
useCreateIndex: true
})
.then(() => console.log('DB Connected'))
// middlewares
app.use(morgan('dev'))
app.use(bodyParser.json())
app.use(cookieParser())
app.use(expressValidator())
// routes middleware
app.use('/api', categoryRoutes)
const port = process.env.PORT || 8000
app.listen(port, () => {
console.log(`Server is running on port ${port}`)
})
controllers/category.js
const Category = require("../models/category")
const { errorHandler } =
require("../helpers/dbErrorHandler")
exports.create = (req, res) => {
const category = new Category(req.body)
category.save((err, data) => {
if(err) {
return res.status(400).json({
error: errorHandler(err)
})
}
res.json({ data })
})
}
routes/category
const express = require('express')
const router = express.Router()
const { create } = require('../controllers/category')
router.post('/category/create/:userId', create);
router.param("userId", userById)
module.exports = router
models/category
const mongoose = require('mongoose')
const categorySchema = new mongoose.Schema(
{
name: {
type: String,
trim: true,
required: false,
maxlength: 32
}
},
{ timestamps: true }
);
module.exports = mongoose.model('Category', categorySchema)
config the header request in postman like this
and the body of request
i'm trying to pass the mongodb connection to all the other routes, so i created another file and imported mongoClient there and wrapped connect and getDb in functions so i can connect to the db first from server.js and then access the db from the other files, but idk why i'm getting Cannot read property 'collection' of undefined
server.js
const express = require('express')
const bodyParser = require('body-parser')
const mongodb = require('./mongodb/db.js')
const auth = require('./routes/auth.js')
require('dotenv').config()
const app = express();
app.use(bodyParser.json());
const PORT = process.env.PORT
app.get('/api', (req, res) => {
res.send('Welcome to the api')
})
app.use('/api/auth', auth);
mongodb.connect(() => {
app.listen(PORT, () => {
console.log(`app is listening at http://localhost:${PORT}`)
})
})
./mongodb/db.js
const MongoClient = require('mongodb').MongoClient;
const DB_URL = process.env.DB_URL
const DB_NAME = process.env.DB_NAME
const dbClient = new MongoClient(DB_URL, { useUnifiedTopology: true })
let db;
const connect = (callback) => {
dbClient.connect().then(client => {
db = client.db(DB_NAME)
console.log("connected to db")
}).catch(console.log)
callback()
}
const get = () => {
return db;
}
module.exports = {
connect,
get
};
./routes/auth.js
const express = require('express')
const router = express.Router();
const db = require('../mongodb/db.js');
const smth = db.get();
console.log(smth) //undefined;
const usersCollection = db.get().collection('users');
const authCollection = db.get().collection('auth')
router.post('/login', async (req, res) => {
...
})
router.post('/register', async (req, res) => {
...
})
module.exports = router
You call callback outside of the promise chain in the connect function of ./mongodb/db.js. It's possible that you are running into some async issues there, as the function can return before the promise chain resolves.