Transferring data from react js to mongodb - javascript

I'm trying to send data from the front-end(react js) to the back-end(node js) and then to mongodb database (so it would be saved there). I called the server successfully with the data, but I'm not able to send the date to the database from the server. These are my files.
react js file: ( this function is called when the user enters some text and clicks on a button )
handleSubmit = () => {
console.log("its running");
let databody = {
message: this.state.val,
};
console.log(" the message is :" + this.state.val);
return fetch("http://localhost:5000/stored", {
method: "POST",
body: databody,
headers: {
"Content-Type": "application/json",
},
})
.then((res) => res.json())
.then((data) => console.log(data));
};
index.js - nodejs file: (Here is where I'm getting my error which says "TypeError: connectDB.collection is not a function")
const express = require("express");
const cors = require("cors"); // Importing cors
var request = require("request");
const dotenv = require("dotenv");
const port = 5000;
var util = require("util");
const connectDB = require("./config/db");
require("dotenv").config({ path: "./config/config.env" });
const app = express();
dotenv.config();
const db = connectDB();
app.get("/", (req, res) => {
res.send("Hey there!");
});
app.get("/Pinged", function (req, res) {
res.send("Pinged!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
});
app.use(cors({ origin: "*" }));
app.post("/stored", (req, res) => {
console.log("its running 2: " + req.body);
db.collection().insertOne(req.body, (err, data) => {
if (err) return console.log(err);
res.send("saved to db: " + data);
});
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
db.js file inside config folder:
const mongoose = require("mongoose");
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useUnifiedTopology: true,
useNewUrlParser: true,
});
console.log(`MongoDB Connected : ${conn.connection.host}`);
return conn;
} catch (err) {
console.error(err.message);
process.exit(1);
}
};
module.exports = connectDB;

Here, in db.js you should return conn.connection
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useUnifiedTopology: true,
useNewUrlParser: true,
})
console.log(`MongoDB Connected : ${conn.connection.host}`)
return conn.connection
} catch (err) {
console.error(err.message)
process.exit(1)
}
}

Related

Why do I get `Cannot read properties of undefined (reading 'collection')` when running 'db.collections' in js code

I'm a very beginner with MongoDB and JS
i'm running nodemon app in the terminal
running MONGODB COMPASS in the background
I'm getting the error:
TypeError: Cannot read properties of undefined (reading 'collection')
at D:\Coding\MongoDB\MongoDB Tutorial\app.js:23:24`
afaik I'm supposed to write db.collections and not db.books directly like I do it in Mongo Shell
db.js
const { MongoClient } = require('mongodb')
let dbConnection;
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
let dbName = 'bookstore'
module.exports = {
// establish connection to the db
connectToDb: async (cb) => {
await client.connect()
.then(client => {
dbConnection = client.db(dbName)
return cb()
})
.catch(err => {
console.log(err);
return cb()
})
},
// return connection to the db
getDb: () => dbConnection
}
app.js
const express = require('express');
const { connectToDb, getDb } = require('./db')
// init app & middleware
const app = express();
// db connection
let db
let PORT = 3000;
connectToDb((err)=>{
if (!err) {
app.listen(PORT, () => {
console.log(`app listening on port ${PORT}`);
});
db = getDb();
}
})
// routes
app.get('/books', async (req, res) => {
// db.books in mongosh
const abc = await db.collection('books').find({});
console.log(abc);
res.json({ msg: 'Welcome to the api' })
})

Unexpected token ' in JSON at position 7

Im getting above error when i made a post request from POSTMAN.Everything works fine but only post request getting me error:((
The below is the handler which gets called when post request is made:
exports.createTour = async (req, res) => {
try {
const newTour = await Tour.create(req.body);
res.status(201).json({
status: 'success',
data: {
tour: newTour
}
});
} catch (err) {
res.status(400).json({
status: 'fail',
message: err
});
}
};
tourRoutes.js
This is my routes file........
const express = require('express');
const tourController = require('./../controllers/tourController');
const router = express.Router();
router
.route('/')
.get(tourController.getAllTours)
.post(tourController.createTour);
router
.route('/:id')
.get(tourController.getTour)
.patch(tourController.updateTour)
.delete(tourController.deleteTour);
module.exports = router;
Server.js
This is my server file all server related info is here....
const mongoose = require('mongoose');
const dotenv = require('dotenv');
dotenv.config({ path: './config.env' });
const app = require('./app');
const DB = process.env.DATABASE.replace(
'<password>',
process.env.DATABASE_PASSWORD
);
mongoose
.connect(DB, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true
})
.then(() => console.log('DB connection successful!'));
const port = process.env.PORT || 8080;
app.listen(port, () => {
console.log(`App running on port ${port}...`);
});

Request body undefined in controller Express

I have a problem with my controller when I'm writing console.log(req); I have all the content of the request body but when I write console.log(req.body); is undefined. I'm trying to write my Portfolio with Next.js React and Express.
This is my server index.js:
const express = require('express');
const next = require('next');
const routes = require('../routes');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
// SERVICE
const authService = require('./services/auth');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = routes.getRequestHandler(app);
const config = require('./config');
const portfolioRoutes = require('./routes/portfolio');
const secretData = [
{ id: '1',
title: 'Secret Data',
description: 'plans for build something !'
},
{
id: '2',
title: 'Secret Data2',
description: 'plans for build something2 !'
}
]
//MONGODB
mongoose.connect(config.DB_URI, {useNewUrlParser: true, useUnifiedTopology: true})
.then(() => {
console.log("Db connected");
}).catch(err => console.log(err));
app.prepare()
.then(() => {
const server = express();
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: false }));
var jsonParser = bodyParser.json()
server.use('/api/v1/portfolio', portfolioRoutes);
server.get('/api/v1/secret', authService.checkJWT, (req,res) => {
return res.json(secretData);
})
server.get('/api/v1/ownersite', authService.checkJWT, authService.checkRole('siteOwner'),
(req,res) => {
return res.json(secretData);
})
server.get('*', jsonParser,(req,res) => {
return handle(req,res);
})
server.use(function (err, req, res, next){
if (err.name === 'UnauthorizedError') {
res.status(401).send({title: `Invalid token...`});
}
});
server.use(handle).listen(3000, (err) => {
if(err) throw err
console.log('> Ready on http://localhost:3000');
})
}).catch((ex) => {
console.error(ex.stack)
process.exit(1);
})
This is my routes :
const express = require('express');
const router = express.Router();
const portfolioCtrl = require('../controllers/portfolio');
const authService = require('../services/auth');
router.route('').get(authService.checkJWT, authService.checkRole('siteOwner'),
portfolioCtrl.getPortfolio);
router.route('').post(authService.checkJWT, authService.checkRole('siteOwner'),
portfolioCtrl.savePortfolio);
router.route('/:id').patch(authService.checkJWT, authService.checkRole('siteOwner'),
portfolioCtrl.updatePortfolio);
router.route('/:id').delete(authService.checkJWT, authService.checkRole('siteOwner'),
portfolioCtrl.deletePortfolio);
module.exports = router;
This is my Controller:
savePortfolio: (res, req) => {
console.log(req);
const portfolioData = req.body;
const portfolio = new Portfolio(portfolioData);
portfolio.save((err, createdPortfolio) => {
if(err) {
return res.status(422).send(err);
}
return res.json(createdPortfolio);
})
},
Express route's callback function takes the parameters in the following order:
(req, res, next) =>{...}
req, the request object.
res, the response object.
next, indicating the next middleware function (Optional)
savePortfolio: (res, req) => {...} has the order wrong. That is why req.body would be undefined.
Correction: savePortfolio: (req, res) => {...}

Why does my http request not return a response

I have several routes in my api that work perfectly but while trying to implement a comment system I dont receive any response either from going to the url (node backend) or from postman.
My server JS is as follows and works for post, teams, users, but it does not work for comments.
Server.js File Below:
//load server
const express = require('express');
var cors = require('cors');
const app = express();
const morgan = require('morgan');
const mysql = require('mysql');
const bodyParser = require('body-parser');
const multer = require('multer');
//db
const db = require('./config/db');
db
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
//image upload
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public')
},
filename: function (req, file, cb) {
let date = new Date(Date.now());
cb(null, date.getDay() + '-' + date.getDate() + '-' + file.originalname )
}
})
var upload = multer({ storage: storage }).single('file')
const port = process.env.PORT || 5000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}))
app.use(cors());
app.use(express.static('./public'))
app.use(morgan('combined'));
const router = require('./routes/user.js')
const postRoute = require('./routes/post.js');
app.use('/posts', require('./routes/post.js'));
app.use('/teams', require('./routes/teams.js'));
app.use('/comments', require('./routes/comments.js'));
app.use(router)
app.listen(port, () => console.log(`Listening on port ${port}`));
Below are my comment api routes:
const express =require('express');
const mysql = require('mysql');
const db = require('../config/db');
const Comments = require('../models/Comments');
// const connection = getConnection()
const router = express.Router();
const Sequelize = require('sequelize');
router.get('/', (req, res) =>
Comments.findAll().then( comments => {
console.log(comments);
res.json(comments);
// res.sendStatus(200);
})
.catch(err => console.log(err)));
router.get('/:id', (req, res) =>
Comments.findAll({
where: {
postId: req.params.id
}
}).then( comments => {
console.log(comments);
res.json(comments);
// res.sendStatus(200);
})
.catch(err => console.log(err)));
router.post('/add/:id', (req, res) => {
Comments.create(req.body).then(comments => {
console.log(req.body)
res.json(comments);
console.log(comments)
})
.catch(err => console.log(err))
});
module.exports = router;
Im posting my Teams Api Route To Show what i have that has been working perfectly for me:
//will contain all user routes
const express =require('express');
const mysql = require('mysql');
const db = require('../config/db');
const Teams = require('../models/Teams');
// const connection = getConnection()
const router = express.Router()
const Sequelize = require('sequelize');
//find all teams
router.get('/', (req, res) =>
Teams.findAll().then( team => {
console.log(team);
res.json(team);
// res.sendStatus(200);
})
.catch(err => console.log(err)));
//find Team by ID
router.get('/:id', (req, res) =>
Teams.findAll({
where: {
id: req.params.id
}
}).then( team => {
console.log(team);
res.json(team);
// res.sendStatus(200);
})
.catch(err => console.log(err)));
//add users image
module.exports = router;
It was because It was expecting a request, and i wasnt giving it one. Have to just return response.
router.get('/').then(res => {
Comments.findAll().then(comments => {
console.log(comments);
res.json(comments.data);
})
})

Cannot POST to CosmosDB using Angular

I am trying to post to my cosmosDB using Angular. I can GET just fine, but POST returns with a 404 error in Postman. I am new to routes and APIs so I am a little lost on what is causing the issue.
Here is my index.js
const bodyParser = require('body-parser');
const path = require('path');
const routes = require('./routes');
const root = './';
const port = process.env.PORT || '3000';
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(root, 'dist/checkin')));
app.use('/api', routes);
app.get('*', (req, res) => {
res.sendFile('dist/checkin/index.html', {root});
});
app.listen(port, () => console.log(`API running on localhost:${port}`));
My routes.js
const contactService = require('./contact.service');
const router = express.Router();
router.get('/contacts', (req, res) => {
contactService.getContacts(req, res);
});
router.post('/contact/', (req, res) => {
contactService.postContact(req, res);
});
module.exports=router;
My contact.service.js which contains all of my operations (Just GET and POST right now)
const ReadPreference = require('mongodb').ReadPreference;
require('./mongo').connect();
function getContacts(req, res) {
const docquery = Contact.find({}).read(ReadPreference.NEAREST);
docquery
.exec()
.then(contacts => {
res.status(200).json(contacts);
})
.catch(error => {
res.status(500).send(error);
return;
});
}
function postContact(req, res) {
const originalContact = { uid: req.body.uid, name: req.body.name, description: req.body.description };
const contact = new Contact(originalContact);
contact.save(error => {
if (checkServerError(res, error)) return;
res.status(201).json(contact);
console.log('Contact created successfully!');
});
}
function checkServerError(res, error) {
if (error) {
res.status(500).send(error);
return error;
}
}
module.exports = {
getContacts,
postContact
};
Input is obtained through an HTML forum which is picked up and sent through
return this.http.post<Contact>(`${api}/contact/`, contact);
}

Categories