how to get all of registered users - javascript

How can I get all the registered users in my course-booking system?
this is my controllers user.js
const User = require("../models/User") //import user model
const bcrypt = require("bcrypt") //import bcrypt
const auth = require("../auth")
module.exports.getAllUsers = (params) => {
return User.find(params.userId).then(resultFromFind => {
return resultFromFind
})
}
and this is my routes user.js
const express = require("express")
const router = express.Router()
const UserController = require("../controllers/user")
const auth = require("../auth")
router.get('/all', auth.verify, (req, res) => {
const users = auth.decode(req.headers.authorization)
UserController.getAllUsers().then(user => res.send(user))
})
I don't know why I get this error on my console.. please help
GET http://localhost:3000/api/users/all 500 (Internal Server Error)

You need to pass the params as a parameter of getAllUsers()
const express = require("express")
const router = express.Router()
const UserController = require("../controllers/user")
const auth = require("../auth")
router.get('/all', auth.verify, (req, res) => {
const users = auth.decode(req.headers.authorization)
UserController.getAllUsers(req.params).then(user => res.send(user)) // <------------------------
})

Related

Error: Route.get() requires a callback function but got a [object Undefined] in Node.js

I am getting the Error: Route.get() requires a callback function but got a [object Undefined]
while running my app.js file. I am following the freecodecamp tutorial "4 nodejs project", the
error is in task manager app.
my app.js
const express = require('express')
const app = express()
const tasks = require('./routes/tasks') //middleware
app.use(express.json())
//routes app.get('/hello',(req,res) => {
res.send('task manager app')
})
app.use('/api/v1/tasks',tasks)
const port = 3000
app.listen(port,console.log(Server is listening on port ${port}...))
routes/tasks.js
const express = require('express')
const router = express.Router()
const { getAllTasks,
createTask,
getTask,
updateTask,
deleteTask, } = require('../controllers/tasks')
router.route('/').get(getAllTasks).post(createTask)
router.route('/:id').get(getTask).patch(updateTask).delete(deleteTask)
module.exports = router
controllers/tasks.js
const getAllTasks = (req,res)=\> {
res.send('all items')
}
const createTask = (req,res) =\> {
res.send('create task')
}
const getTask = (req,res) =\> {
res.send('get single task')
}
const updateTask = (req,res) =\> {
res.send('update task')
}
const deleteTask = (req,res) =\> {
res.send('delete task')
}
module.export = {
getAllTasks,
createTask,
getTask,
updateTask,
deleteTask,
}
no error should be there but throws the above error.
You are trying to get your controller function in your root for more details you can check out here moz
router.get('/',getAllTasks) //example

Mongoose import from file "buffering timed out"

I'm trying to import some .json data to mongo, but when trying to save() a person, it just waits some seconds and then crashes with an error: MongooseError: Operation people.insertOne() buffering timed out after 10000ms
It's weird, because when I'm doing POST request it works fine, the person is added correctly.
I wrote some console.logs for help, and it prints the person correctly (inside for loop).
My import script file:
const fs = require('fs/promises')
const express = require('express')
const Person = require('../models/people')
const router = express.Router()
const importData = async () => {
const data = await fs.readFile('./people.json')
console.log(data)
const dataParsed = JSON.parse(data)
for(const person of dataParsed) {
const personToSave = new Person({
firstName: person.firstName,
lastName: person.lastName
})
console.log(personToSave)
await personToSave.save()
}
}
importData()
module.exports=router
My connect:
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const people = require('./routers/people');
const pets = require('./routers/pets');
const aggregate = require('./routers/aggregate');
const port = 3000;
app.use(express.json());
app.use('/people', people);
app.use('/pets', pets);
app.use('/aggregate', aggregate);
mongoose.connect('mongodb://localhost:27017/people').then(() => {
console.log('Connected to mongoDB');
app.listen(port, () => {
console.log(`App is listening at port ${port}`);
});
});

How to use middleware with router.verb() in koa

I'm using Koa.js and I was wondering how I could use a middleware with router.verb()
As mentioned here router.use([path], middleware) I tried like below.
The console.log() trigger but the users.list is not called
My main objective is to do an auth middleware
const Router = require("#koa/router");
const router = new Router();
const users = require("./Controllers/users/index.js");
router.use("/user", (ctx, next) => {
console.log(ctx);
next();
});
router.get("/user", users.list)
I don't get any error messages but the users.list don't execute.
Then i tried this
router.get("/user", (ctx, next) => {
console.log(ctx);
next();
}, users.list)
But i don't get any change and I feel like I don't understand something, but can't figure out what
In my index.js
const Koa = require("koa");
const router = require("./Routes");
const bodyParser = require("koa-bodyparser");
const cors = require("#koa/cors");
const serve = require("koa-static");
const path = require("path");
const errorHandler = require("./Middlewares/errorHandler");
const app = new Koa();
app.use(errorHandler)
.use(bodyParser())
.use(cors())
.use(router.routes())
.use(serve(path.join("public", "ads")))
.use(router.allowedMethods());
in my controller
const { Users } = require("../../Models");
module.exports = {
list: async (ctx, next) => {
let AllUsers = await Users.findAll();
ctx.body = AllUsers;
}
}
I got it working with adding await next()
router.use("/ads", async (ctx, next) => {
console.log(ctx);
await next();
});
Since my controller is an async function I get my explanations from here -> async/await always returns promise

Route.delete() requires a callback function but got a [object Object]

I have node-express app where I have bunch of Routes for login, logout and signup and one Route for checking authorised Route which can be accessed only through providing authToken. I moved the Routes to separate Route file and I got the above error.
This is my Users Routes File:
const express = require('express');
const authenticate = require('./../middleware/authenticate');
const router = express.Router();
const {User} = require('./../models/user');
router.post('/',(req, res) => {
var body = _.pick(req.body,['email','password']);
var user = new User(body);
user.save().then(() => {
return user.generateAuthToken()
}).then((token) => {
res.header('x-auth', token).send(user);
}).catch((e) => {
res.status(400).send(e);
});
});
router.post('/login',(req, res) => {
var body = _.pick(req.body, ['email', 'password']);
User.findByCredentials(body.email, body.password).then((user) => {
return user.generateAuthToken().then((token) => {
res.header('x-auth', token).send(user);
});
}).catch((e) => {
res.status(400).send(e);
});
});
router.delete('/logout',authenticate, (req, res) => {
req.user.removeToken(req.token).then(() => {
res.status(200).send();
},(e) => {
res.status(400).send(e);
}) ;
});
router.get('/me',authenticate, (req,res) => {
res.send(req.user);
});
module.exports = router;
Following is my main server.js file:
const express = require('express');
const _ = require('lodash');
var app = express();
const usersRoutes = require('./routes/users');
app.use(express.json());
app.use('/users', usersRoutes);
var {mongoose} = require('./db/mongoose');
var {User} = require('./models/user');
var {authenticate} = require('./middleware/authenticate');
const port = process.env.PORT || 3000 ;
app.listen(port, () => console.log(`Listening on ${port}...`))
I have a model/Schema(mongoose) file for User so If You feel you need that I am ready to edit my question. Thanks.
The problem is that router.delete is expecting a function on the middleware parameter (like you did in your server.js file with app.use(express.json())) so it can be used like a callback which gets called whenever a request reach your route.
Try changing authenticate to authenticate().
It seems like in your users routes file you are importing the entire module who contains the authenticate function, so when try to access it like a function you'll get an error. You need to import it like you did in your server.js file.
Change the line const authenticate = require('./../middleware/authenticate'); for const {authenticate} = require('./../middleware/authenticate');.

Firebase Cloud Function Auth Trigger not firing

I'm using Express in my Cloud Function with multiple routes, and I'm trying to add in a function that when triggered, will pull the users Gravitar and add it to their user object.
The problem I'm having is that I cannot get the onCreate function to fire, and I suspect it's to do with how I'm attempting to export it.
My index.js looks like the following:
const admin = require("firebase-admin");
const functions = require("firebase-functions");
const usersApi = require("./api/users")
const paymentsApi = require("./api/payments")
const express = require('express');
const cors = require('cors');
const app = express();
const checkHeader = async(req, res, next) => {
if(req.headers.authorization) {
admin.auth().verifyIdToken(req.headers.authorization)
.then(token => {
req.uid = token.uid;
req.email = token.email;
req.stripeID = token.stripeID || null;
return next();
})
.catch(e => {
return next(e.errorInfo.code)
})
} else {
return next('No token found');
}
}
app.use(cors({origin: true}));
app.use(express.urlencoded({extended: true}));
app.use(express.json());
app.use(checkHeader);
app.disable("x-powered-by");
app.use("/users", usersApi)
app.use("/payments", paymentsApi)
const setupUser = functions.auth.user().onCreate((user) => {
console.log("onCreate")
console.log(user)
})
module.exports = {
api: functions.https.onRequest(app),
setupUser
}
The api endpoint works fine, however I can't get the onCreate function to trigger when a user is created.

Categories