Cant send POST request to db - javascript

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()

Related

.env variables are undefined

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')});

MongoDb query return empty object

I'm trying to perform a simple .find() query on my mongodbAtlas, but the result of this query is an empty object.
this is my server file:
require("dotenv").config({ path: "./config.env" });
const { MongoClient, ServerApiVersion } = require("mongodb");
const express = require("express");
const { ServiceBroker } = require("moleculer");
const AUTH_SERVICE = require("./controller/services/auth/auth.service");
global.broker = new ServiceBroker({
nodeID: "auth",
});
const app = express();
app.use(express.json());
app.use("/auth", require("./routes/auth"));
const { PORT, URI } = process.env || 5000;
global.broker.createService(AUTH_SERVICE);
const start = async () => {
const dba = await MongoClient.connect(URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
global.db = dba.db("Auth");
try {
await dba.connect();
console.log("DATABASE CONNESSO CON SUCCESSO📡");
} catch (e) {
console.error(e);
}
await global.broker.start();
app.listen(PORT, () => console.log(`PORT IT'S UP AND RUNNING 🚀 ON ${PORT}`));
};
start();
this is my routes file:
const express = require("express");
const router = express.Router();
router.get("/register", async (req, res) => {
const data = global.db.collection("Users").find({}).toArray();
res.send(data);
});
module.exports = router;
this is how my document is populated:
{"_id":{"$oid":"6297bbc83a95b81d74882f65"},"username":"Test","email":"test#gmail.com","password":"1234"}
I think you are missing the "await" keyword after const data..... as API data fetching calls are asynchronous and required promise/ async-await to handle. Being async in nature, it moves forward to the next instruction and returns an empty array.
const express = require("express");
const router = express.Router();
router.get("/register", async (req, res) => {
const data = await global.db.collection("Users").find({}).toArray();
res.send(data);
});
module.exports = router;

Getting error <pre>Cannot POST /api/category/create/62545ea650265cda5b08f10d</pre>

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

Cannot read property 'collection' of undefined MongoDB nodejs driver

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.

not able to hit the router in the browser when I hit the url

I have a working codebase where they have already setup node proxy and jwt.
my server is running at 1010 port
but when I hit this url http://localhost:1010/sampletest
I am getting an error in the browser screen Cannot GET /sampletest
even I hit this url http://localhost:1010/jump/api/v1 but still I am getting same error
can you tell me how to fix it or am I missing anthing in the configurations
providing my index.js and server.js code below
sports.js
const express = require('express');
const axios = require('axios');
const mime = require('mime-types');
const router = express.Router();
const ResponseUtil = require('../../utils/ResponseUtil');
const AppConstants = require('../../../constants/AppConstants');
const credentials = require('../../../internals/credentials.json');
const memberGroupingHelper = require('../../helpers/rank/memberGrouping');
const exportHelper = require('../../helpers/rank/rankExportHelper');
const formatExportData = require('../../helpers/rank/formatExportData');
const rankCommonHelper = require('../../helpers/rank/rankCommonHelper');
const rankProvDataHelper = require('../../helpers/group/getProvData');
//const aggregateHelper = require('../../helpers/group/aggregateFilter');
const { rankAggregatelastrsApi } = require('jump-svc-utils');
//router.get('/:searchMode/:lastrSearch', (req, res, next) => {
router.get('/sampletest', (req, res, next) => {
const { originalUrl } = req;
//console.log(" originalUrl ", originalUrl);
const mode = req.params.searchMode;
const value = encodeURIComponent(req.params.lastrSearch);
console.log("document 40--->", mode);
console.log("for document Testing0--->", mode);
const url = `/jkjkjk/sdjksdjkjksdjksd/sdklsdlksdklsdkl`;
axios.get(AppConstants.GET_JWT_TOKEN_URL, {
auth: {
username: credentials.auth.racfId, password: credentials.auth.password
}
})
.then((jwtResponse) => {
// var jwtToken = `Bearer ${jwtResponse.data.jwt}`;
var jwtToken = `Bearer 787878bjhbnmnmmwqdqwqwqwqwqwqwqwqwqwqwqwqwqwqwqwqwqwqw`;
axios.get(url, { headers: { "Authorization": jwtToken } })
.then((response) => {
console.log("document then0--->", response);
const file = Buffer.from(response.data.content, 'base64');
const fileType = mime.contentType(response.data.contentInfo.fileType);
const fileExtension = response.data.contentInfo.fileType.toLowerCase();
const fileName = `filename=${response.data.contentInfo.id}.${fileExtension}`;
res.set('Content-Type', fileType);
res.set('Content-disposition', `attachment; ${fileName}`);
res.send(file);
})
.catch((e) => {
console.log("e catch document0--->", e);
console.log("e.message catch document0--->", e.message);
console.log("catch document--->", e.response);
if (e.response) {
return res.status(e.response.status).send(e.response.data);
}
res.status(500).send(e.message || 'Something wrong');
});
});
ResponseUtil.callService(res, url);
});
module.exports = router;
index.js
const express = require('express')
const app = express()
const port = 1010
const jumpServices = require('./services/jump');
const compression = require('compression');
var BodyParser = require('body-parser');
const glob = require('glob');
const path = require('path');
app.use('/jump/api/v1', jumpServices);
app.use(BodyParser.json());
app.use(BodyParser.urlencoded({
extended: true
}));
//app.use(compress())
// app.use(compression());
// include all the controllers
const controllers = glob.sync(path.join(__dirname, '/controllers/**/*.js'));
console.log("controllers--->", controllers);
controllers.forEach((controllerFileName) => {
require(controllerFileName)(app); //eslint-disable-line
});
app.listen(port, (err) => {
if (err) {
return console.log('something bad happened', err)
}
console.log(`server is listening on ${port}`)
})
I don't see any calls registering your sub Routers with the top level express application. You should need to call app.use for each of your sub routers.

Categories

Resources