No response from node js (mongoose) - javascript

I send request from React with:
export const loadItems = () => async dispatch => {
await axios
.get("http://localhost:8000/api/users")
.then(response => {
console.log(response.users);
dispatch(dataLoaded(response.users));
})
.catch(err => {
dispatch(dataLoadFailed(err));
});
};
But there is no response, and the server does not take request, here is my server app code:
server.js
// a lot of requires
const todoRoutes = require("./routes/serverRoute");
const url = "mongodb://localhost:27017/taskManager";
const app = express();
mongoose.Promise = global.Promise;
mongoose.connect(
url,
{ useNewUrlParser: true },
function(err) {
if (err) {
console.log(err);
} else console.log("Database connected");
}
);
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "/public/index.html"));
});
// cors allow
app.use("/api", todoRoutes);
app.listen(8000, () => {
console.log("API started");
});
And this is a controller I use, it's all good with Schema and DB, I checked with output to console from the node, users is defined and contains data
const mongoose = require("mongoose");
const User = require("../models/UserModel");
module.exports = {
getUsers(req, res) {
User.find().exec((err, users) => {
if (err) {
console.log(err);
return res.send({ err });
} else {
console.log(users);
return res.send({ users });
}
});
}
};
And this is my router:
module.exports = router => {
router.get('/users', userController.getUsers);
}

Ok, I got it on my own. Problem was here:
router.get('/users', userController.getUsers);
It supposed to be like this:
router.get('/users', userController.getUsers());

Related

Why am I getting ReferenceError: db is not defined

For some reason I cannot get axios to connect to the DB. Its is a MSQL server and when I use app.get in the server file I can get data returned but when using express DB connection just doesn't persist. In postman I can return a result with all my code on server.js receiving the entire table. This is what I want. When moving everything to axios and routing it to have less code on my server nothing returns anymore. nothing is broken except i get ReferenceError: db is not defined in nodemon.
HomePage
const express = require('express')
const app = express()
const mysql = require('mysql')
const morgan = require('morgan')
//middleware
app.use(express.json())
app.use(morgan('dev'))
//Connect to DB
const db = mysql.createConnection({
user : 'root',
password : '******',
database : 'avengers'
})
db.connect((err) => {
if(err){
console.log(err)
}
console.log('MySql Connected...')
})
//Routes
app.use('/avengers', require('./routes/avengerRouter.js'))
//error handling
app.use((err, req, res, next) => {
console.log(err)
return res.send({errMsg: err.message})
})
app.listen(9000, () => {
console.log("The server is running on port 9000")
})
Server.js
import React, {useState, useEffect} from 'react'
import axios from 'axios'
import AvengersTable from './AvengerTable.js'
function delay(time) {
return new Promise(resolve => setTimeout(resolve, time));
}
export default function Main(){
const [tableState, setTableState] = useState('')
useEffect(() => {
async function getTableData() {
axios.get('/avengers')
await delay(300)
.then(res => {
// setTableState(res.data)
console.log(res)
})
.catch(err => console.log(err.response.data.errMsg))
} getTableData()
}, [])
return (
<div className="Main">
{/* <AvengersTable tableState={tableState}/> */}
</div>
)
}
avengerRouter.js
const express = require('express');
const avengerRouter = express.Router();
function delay(time) {
return new Promise(resolve => setTimeout(resolve, time));
}
avengerRouter
// all data from avengers table http://localhost:9000/avengers
.get('/', (req, res) => {
let sql = 'SELECT * FROM avengers.avengers'
db.query(sql, (err, result) => {
if(err) console.log(err)
console.log(result)
})
})
module.exports = avengerRouter;
Create a file named db.js that includes a DB connection.
const mysql = require('mysql')
const db = mysql.createConnection({
user : 'root',
password : '******',
database : 'avengers'
});
export default db;
Usage of db at top of your HomePage
const db = require('./db.js');
db.connect((err) => {
if(err){
console.log(err)
}
console.log('MySql Connected...')
});
// Other codes goes below
...
And finally usage in your avengerRoute.js
const express = require('express');
const avengerRouter = express.Router();
// Forgotten line here
const db = require('./db.js');
function delay(time) {
return new Promise(resolve => setTimeout(resolve, time));
}
avengerRouter
// all data from avengers table http://localhost:9000/avengers
.get('/', (req, res) => {
let sql = 'SELECT * FROM avengers.avengers'
db.query(sql, (err, result) => {
if(err) console.log(err)
console.log(result)
})
})
module.exports = avengerRouter;

how to fix Error with Nodejs and 'gridfs-stream'

I am trying to follow along a tutorial and use nodejs with 'gridfs-stream' along with a react front end. The tutorial is from last year in 2020.
Here is my code.
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const cors = require('cors')
const multer = require('multer');
const {GridFsStorage} = require('multer-gridfs-storage');
const Grid = require('gridfs-stream');
const path = require('path');
const Pusher = require('pusher')
const mongoPosts = require ('./mongoPosts.js')
// const currentTournamentControllers = require('../controllers/currenttournament-controllers');
const app = express();
const port = process.env.PORT || 9000
app.use(bodyParser.json())
app.use(cors())
const mongoURI = 'mongodb+srv://fbclient:rmbmbkvZVHw3e6OK#cluster0.emaw1.mongodb.net/myFirstDatabase?retryWrites=true&w=majority'
const conn = mongoose.createConnection(mongoURI);
mongoose.connect(mongoURI)
mongoose.connection.once('open', () => {
console.log('DB Connected')
})
let gfs
conn.once('open', () => {
// Init stream
gfs = Grid(conn.db, mongoose.mongo);
gfs.collection('images');
});
const storage = new GridFsStorage({
url: mongoURI,
file: (req, file) => {
return new Promise((resolve, reject) => {{
const filename = `image-${Date.now()}${path.extname(file.originalname)}`
const fileInfo = {
filename: filename,
bucketName: 'images'
}
resolve (fileInfo)
}})
}
})
const upload = multer({storage})
app.get('/', (req, res) => res.status(200).send('hello world'))
app.post('/upload/image', upload.single('file'), (req, res) => {
res.status(201).send(req.file)
})
app.post('/upload/post', (req, res) => {
const dbPost = req.body
console.log(dbPost)
mongoPosts.create(dbPost, (err, data) => {
if(err){
res.status(500).send(err)
} else {
res.status(201).send(data)
}
})
})
app.get('/retrieve/image/single', (req, res) => {
console.log(req.query.name)
gfs.files.findOne({filename: req.query.name}, (err, file) => {
if(err) {
res.status(500).send(err)
} else {
console.log(file)
if(!file || file.length === 0) {
console.log("hi i errored out")
res.status(404).json({err: 'file not found'})
} else {
console.log("hi i am trying to read")
const readstream = gfs.createReadStream(file.filename)
readstream.pipe(res)
}
}
})
})
app.get('/retrieve/posts', (req, res) => {
mongoPosts.find((err, data) => {
if(err){
res.status(500).send(err)
} else {
data.sort((b,a) => {
return a.timestamp - b.timestamp
})
res.status(200).send(data)
}
})
})
app.listen(port, () => console.log(`listening on localhost:${port}`))
The problem is with readstream. When I am trying to retrieve the data it shows the error
TypeError: grid.mongo.ObjectID is not a constructor
I did some debugging and figured out that this can be fixed by changing a value inside the gridfs.js file in the node_modules. The change being suggested on Stack Overflow was this :-
this._store = new grid.mongo.GridStore(grid.db, this.id || new grid.mongo.ObjectID(), this.name, this.mode, options);
changed to
this._store = new grid.mongo.GridStore(grid.db, this.id || new grid.mongo.ObjectId(), this.name, this.mode, options);
The suggestion was to change the grid.mongo.ObjectID value to grid.mongo.ObjectId. So I did that. Now the error coming out is as follows:-
TypeError: grid.mongo.GridStore is not a constructor
For this I am not getting any fixes on stack overflow or any other websites. Can someone please help

How can we add collections in mongoDB dynamically( through users)?

Adding collections manually is easy but adding it dynamically giving me unexpected answer.
I am getting a collection name from frontend to backend using promt and axios but when I am doing
const variable_from_frontEnd = mongoose.model(variable_from_frontEnd, Schema);
it is not adding any collections.
import express from "express";
import mongoose from "mongoose";
import Messages from "./messages.js";
import cors from "cors";
// app configuration
const app = express();
const port = process.env.PORT || 9000;
const pusher = new Pusher({
appId: "1183689",
key: "c9fa659fc6b359a23989",
secret: "9da56a5db535e10c7d95",
cluster: "eu",
useTLS: true
});
//middleware
app.use(express.json());
app.use(cors());
// DB Configuration
const url = "mongodb+srv://suraj_bisht_99:zoe6B82AZjaLXgw7#cluster0.zp9dc.mongodb.net/Whatsapp_MERN?retryWrites=true&w=majority";
mongoose.connect(url, {useCreateIndex: true, useNewUrlParser: true, useUnifiedTopology: true})
.then(()=> console.log('mongoDB is connected'))
.then(err => console.log(err));
const groupSchema = mongoose.Schema( {
message: String,
name: String,
timestamp: String,
received: Boolean,
});
// API routes
app.get("/", (req, res) => {
res.status(200).send("Hello World");
})
app.get("/messages/sync", async (req, res) => {
await Messages.find( (err, data) => {
if(err){
console.log(err);
res.status(500).send(err);
}else{
res.status(200).send(data);
}
})
})
app.post("/messages/new", async (req, res) => {
try{
const newMessage = new personalGroup(req.body);
const newMessageCreated = await newMessage.save();
res.status(201).send(newMessageCreated);
}
catch(err){
res.status(400).send(err);
}
});
// route for creating new collection in mongoDB
app.post("/room/new", async (req, res) => {
try{
let groupName = req.body.room;
groupName = mongoose.model(groupName, groupSchema);
if(!groupName){
console.log("error is occured");
}else{
console.log(groupName);
}
}
catch(err){
res.status(400).send(err);
}
})
// listening part
app.listen(port, () => console.log(`listening on port number ${port}`));
Let's say I have type a collection name "studyGroup" from frontend then
console is giving me
Model { studyGroup }
Can someone help me why it is happening and how can I add collections manually.

Cannot get "/tinder/cards" route but getting "/" route

This below code is my first react application. After running server.js. After entering "http://localhost:8001/" I got HELLO!!. I expected after entering "http://localhost:8001/tinder/cards" url on chrome and postman too I get following error.
error message: "Cannot GET /tinder/cards".
this is my server.js file.
import mongoose from 'mongoose'
import Cors from 'cors'
import Cards from './dbCards.js'
// App Config
const app = express()
const port = process.env.PORT || 8001
const connection_url = 'mongodb+srv://admin:0tRkopC1DKm4ym4V#cluster0.iw73w.mongodb.net/tinderDB?retryWrites=true&w=majority'
// Middlewares
app.use(express.json())
app.use(Cors())
app.use('/',router);
// DB Config
mongoose.connect(connection_url, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
})
// API Endpoints
app.get("/", (req, res) => res.status(200).send("HELLO!!"))
app.get("/hello", (req, res) => res.status(200).send("Oooooooo!!"))
app.post("/tinder/cards", (req, res) => {
const dbCard = req.body
Cards.create(dbCard, (err, data) => {
if(err) {
res.status(500).send(err)
} else {
res.status(201).send(data)
}
})
})
app.get("/tinder/cards", (req, res) => {
Cards.find((err, data) => {
if(err) {
res.status(500).send(err)
} else {
res.status(200).send(data)
}
})
})
// Listener
app.listen(port, () => console.log(`listening on location: ${port}`)) ```
try this in your app.get('/tinder/cards') section:
// Doing it the Asynchronous way
app.get('/tinder/cards', async (req, res) => {
try { // Trying for getting the cards
const allCards = await Cards.find(); // Getting the cards
res.status(200).send(allCards); // Sending the cards
} catch (error) { // Catching the error
res.status(500).send(error); // Sending the error
}
});
Try to replace cards with card in the URL. Have a look at the image for the same.

Access req.user to save id to mongoDB

I'm currently having an issue with figuring out how I can access req.user so I can get the logged in users id and save it with the items that they save on the web page. That way when they load the web page they only get their items. The only place I know where I have access to req.user is in my /router/auth.js file. I want to figure out a way to access it in a different router file.
router/auth.js
const express = require('express');
const passport = require('passport');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const config = require('../config');
const router = express.Router();
const createAuthToken = function (user) {
return jwt.sign({ user }, config.JWT_SECRET, {
subject: user.username,
expiresIn: config.JWT_EXPIRY,
algorithm: 'HS256'
});
};
const localAuth = passport.authenticate('local', { session: false });
router.use(bodyParser.json());
router.post('/login', localAuth, (req, res) => {
const authToken = createAuthToken(req.user.serialize());
res.json({ authToken });
});
const jwtAuth = passport.authenticate('jwt', { session: false });
router.post('/refresh', jwtAuth, (req, res) => {
const authToken = createAuthToken(req.user);
res.json({ authToken });
});
/router/portfolio.js
router.post('/:id', (req, res) => {
const id = req.params.id;
const { holdings } = req.body;
CryptoPortfolio.findOne({ id }, (err, existingCoin) => {
if (existingCoin === null) {
getCoins(id)
.then(x => x[0])
.then(value =>
CryptoPortfolio.create({
id: value.id,
holdings,
_creator: this is where I want to add req.user.id
}).then(() => value))
.then(newItem => {
res.status(201).json(newItem);
})
.catch(err => {
console.error(err);
res.status(500).json({ message: 'Internal server error' });
});
} else {
const capitalizedId = id.charAt(0).toUpperCase() + id.slice(1);
res.json(`${capitalizedId} already in watchlist`);
}
});
});
You can define global variable and use it using middleware.
app.js
// Global Vars
app.use(function (req, res, next) {
res.locals.user = req.user
next();
});
route.js
router.get('/', function(req, res) {
CryptoPortfolio.find({}, function(err, crypto) {
console.log('CryptoPortfolio : ',crypto);
res.render('view/crypto', {
user : res.locals.user // <= here
});
});
});
I hope it would be helpful :)
I figured out that I wasn't using the code below on any of the necessary routes. Implemented it and I can now access req.user.
const jwtAuth = passport.authenticate('jwt', { session: false });

Categories

Resources