passport.use is not a function - javascript

I am trying to add passport service to my app , but I am getting the following error,
I have already installed all the dependencies and tried searching for this error but got none , please Help
passport.use(new JwtStrategy(opts, function(jwt_payload, done){
TypeError: passport.use is not a function
at module.exports (/home/udit/Goserv/app/config/passport.js:11:14)
at Object.<anonymous> (/home/udit/Goserv/app/server/server.js:9:45)
at Module._compile (module.js:410:26)
at Object.Module._extensions..js (module.js:417:10)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Function.Module.runMain (module.js:442:10)
at startup (node.js:136:18)
at node.js:966:3
Here is the passport.js file:
var JwtStrategy = require('passport-jwt').Strategy,
ExtractJwt = require('passport-jwt').ExtractJwt;
var User = require('../model/user.js');
var config = require('../config/database');
module.exports = function(passport){
var opts = {};
opts.secretOrKey = config.secret;
opts.jwtFromRequest = ExtractJwt.fromAuthHeader();
passport.use(new JwtStrategy(opts, function(jwt_payload, done){
User.find({id: jwt_payload.id}, function(err, user){
if (err) {
return done(err, false);
}
if (user) {
return done(null, user);
} else {
return done(null, false);
}
})
}));
}

you will get this error if import it like this
import * as passport from 'passport';
should be
import passport from 'passport';

You need to require passport.js from your app.js file with the following command:
require('./config/passport')(passport);
All the passport-related commands in your app.js file should be:
const passport = require('passport');
app.use(passport.initialize());
app.use(passport.session());
require('./config/passport')(passport);

Related

TypeError('app.use() requires a middleware function')

enter image description here
here's the app.js(--please find attached image):
//here's the app.js
const express = require("express");
const app = express();
app.use(express.json());
const morgan = require("morgan");
const mongoose = require("mongoose");
const cors = require("cors");
require("dotenv/config");
const authJwt = require("./helpers/jwt");
const errorHandler = require("./helpers/error-handler");
app.use(cors());
app.options('*', cors());
//middleware
app.use(morgan("tiny"));
app.use(authJwt());
app.use(errorHandler()); //-> **this isn't correct?**
//Importing routing of products
const categoriesRoutes = require("./routes/categories");
const productsRoutes = require("./routes/products");
const usersRoutes = require("./routes/users");
const ordersRoutes = require("./routes/orders");
const req = require("express/lib/request");
const res = require("express/lib/response");
const api = process.env.API_URL;
//routers
app.use(`${api}/products`, productsRoutes);
app.use(`${api}/categories`, categoriesRoutes);
app.use(`${api}/orders`, ordersRoutes);
app.use(`${api}/users`, usersRoutes);
//Database
mongoose
.connect(process.env.CONNECTION_STRING, {
useNewurlParser: true,
useUnifiedTopology: true,
dbName: "eshop-database",
})
.then(() => {
console.log("database connection is ready");
})
.catch((err) => {
console.log(err);
});
//Server
app.listen(3000, () => {
console.log("Server is Running http://http://localhost:3000");
});
//error image
//here's the error handler code
function errorHandler(err, req, res, next){
if (err) {
res.status(500).json({message: err})
}
}
module.exports = errorHandler;
> Blockquote (--please find attached image)
here's the error
C:\Users\steve\Backend\node_modules\express\lib\application.js:210
throw new TypeError('app.use() requires a middleware function')
^
TypeError: app.use() requires a middleware function
at Function.use (C:\Users\steve\Backend\node_modules\express\lib\application.js:210:11)
at Object.<anonymous> (C:\Users\steve\Backend\app.js:17:5)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47
Your error handler function is correct, but the problem is that you're calling the function instead of passing it directly to your express app.
Remove the parenthesis after the errorHandler and it should work.
app.use(errorHandler); // Don't call errorHandler, express will call it
Think of it like this.
if I just call errorHandler() in any context it won't return anything.
That means that errorHandler() evaluates to undefined.
Now in your code, when you do app.use(errorHandler()) instead of evaluating to the following:
app.use(function(err, req, res, next){
if (err) {
res.status(500).json({message: err})
}
});
Your code is actually evaluating to
app.use(undefined);
and so express is throwing an error because undefined is not a function.

Type error: cannot find module body-parser

I tried making a project on my own and this error happened. I couldn't fix it. It just somehow happens and I am so confused where to start looking for the error.
app.js
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.set('view engine', 'ejs');
app.set('views', 'views');
const adminData = require('./routes/admin');
const shopRoutes = require('./routes/shop');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/admin', adminData.routes);
app.use(shopRoutes);
app.use((req, res, next) => {
res.status(404).render('404', { pageTitle: 'Page Not Found' });
});
app.listen(3000);
admin.js
const path = require('path');
const express = require('express');
const rootDir = require('../util/path');
const router = express.Router();
const products = [];
// /admin/add-product => GET
router.get('/add-product', (req, res, next) => {
res.render('add-product', {
pageTitle: 'Add Product',
path: '/admin/add-product',
formsCSS: true,
productCSS: true,
activeAddProduct: true
});
});
// /admin/add-product => POST
router.post('/add-product', (req, res, next) => {
products.push({ title: req.body.title });
res.redirect('/');
});
exports.routes = router;
exports.products = products;
shop.js
code snippet of shop.js
This is my error.
I am making a webpage for the first time using this.
internal/modules/cjs/loader.js:638
throw err;
^
Error: Cannot find module 'body-parser'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
at Function.Module._load (internal/modules/cjs/loader.js:562:25)
at Module.require (internal/modules/cjs/loader.js:692:17)
at require (internal/modules/cjs/helpers.js:25:18)
at Object.<anonymous> (C:\Users\User\Documents\My Website\05-working-on-layout-with-partials\app.js:4:20)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
[nodemon] app crashed - waiting for file changes before starting...
Please try to install the required body-parser module,
Use following command to do so.
npm install body-parser
Please install the dependency i.e body-parser
npm i body-parser --save
Error is on the 4th line of app.js its not getting the body-parser module

How to solve "Router.use() requires a middleware function but got a Object at Function.use" error

I am getting an error when calling my router from my routes directory.I have made some changes in my code around some of the other posts on this issue but I can't get anything to solve.However i am not sure what exactly is wrong with my code below.
This is my error
[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
E:\Program Files\mean apps\shoppinglist\crud-backend\node_modules\express\lib\router\index.js:458
throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
^
TypeError: Router.use() requires a middleware function but got a Object
at Function.use (E:\Program Files\mean apps\shoppinglist\crud-backend\node_modules\express\lib\router\index.js:458:13)
at Function.<anonymous> (E:\Program Files\mean apps\shoppinglist\crud-backend\node_modules\express\lib\application.js:220:21)
at Array.forEach (<anonymous>)
at Function.use (E:\Program Files\mean apps\shoppinglist\crud-backend\node_modules\express\lib\application.js:217:7)
at Object.<anonymous> (E:\Program Files\mean apps\shoppinglist\crud-backend\app.js:42:5)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
at startup (internal/bootstrap/node.js:279:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:752:3)
[nodemon] app crashed - waiting for file changes before starting...
I have this code in my app.js
//importing modules
var express = require('express');
var mongoose = require('mongoose');
var bodyparser = require('body-parser');
var cors = require('cors');
var path = require('path');
var app = express();
const route = require('./routes/route');
//conect to the mongodb
mongoose.connect('mongodb://localhost:27017/shoppinglist');
//on connection
mongoose.connection.on('connected',()=>{
console.log('Connected to database mongodb # 27017');
});
//error
mongoose.connection.on('error',(err)=>{
if(err)
{
console.log('Error in database connection:'+ err);
}
});
//port no
const port = 3000;
//adding middleware - cors
app.use(cors());
//body - parser
app.use(bodyparser.json());
//static files
app.use(express.static(path.join(__dirname, 'public')));
//routes
app.use('/api', route);
//testing server
app.get('/',(req, res)=>{
res.send('foobar');
});
app.listen(port,()=>{
console.log('Server started at port:' + port);
});
I have this code in my route.js
const express = require('express');
const router = express.Router();
const Item = require('../model/shoppingItem');
//retriving data from db
router.get('/items', (req, res, next)=>{
Item.find(function(err, items){
if(err){
res.json(err);
}
else{
res.json(items);
}
});
});
//insert data
router.post('item', (req, res, next)=>{
let newShoppingItem = new Item({
itemName: req.body.itemName,
itemQuantity: req.body.itemQuantity,
itemBought: req.body.itemBought
});
newShoppingItem.save((err, item)=>{
if(err){
res.json(err);
}
else{
res.json({msg: 'Item has been added successfully'});
}
});
});
You are using a module that you never exported.
app.use('/api', route);
but route was never exported - that's your main issue.
in your route module you can wrap everything in export default - alternatively you can use module.exports = router
This is an open source project I was working on try following the structure, if you still have issues let me know.
https://github.com/Muhand/nodejs-server

Express JS REST API with MySQL

I am doing an exercise with Express.js and MySQL. At the moment I have 4 files. The error is,
TypeError: areas.getAreas is not a function
at Object.<anonymous> (/--/--/--/src/routes/userRoutes.js:4:13)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
at Module.require (module.js:597:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/--/--/--/src/app.js:10:20)
at Module._compile (module.js:653:30)
But I am sure I am declaring the variable and function so, I don't understand why is it happening.
I tried to get the value of the variable areas in the userRoutes.js file but console just show me an "{}". I also tried to change the sintaxis of the function of the areas.js file, writing it as function and not like an object.
The main file is, app.js and it contains:
const express = require('express');
const app = express();
const morgan = require('morgan');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const connection = require('/--/--/--/db/connection.js');
const userRoutes = require('/--/--/--/routes/userRoutes.js');
app.set('port', process.env.PORT || 3000);
app.use(morgan('dev'));
app.use(bodyParser.json());
connection(mysql);
userRoutes(app);
app.listen(app.get('port'), ()=> {
console.log('server on port 3000');
});
The next files are:
connection.js
'use strict';
module.exports = function connection(mysql){
mysql.createConnection({
host: 'http://x.x.x.x',
user: 'xxxxxxx',
password: 'xxxxxxx',
database: 'xxxxxxx'
})
};
areas.js
'use strict';
let areasModel = {};
areasModel.getAreas = (callback) => {
if(connection) {
connection.query(
"SELECT * FROM areas",
(err, rows) => {
if(err) {
throw err;
}
else {
callback(null, rows);
}
}
);
}
};
module.exports = areasModel;
userRoutes.js
'use strict';
const areas = require('../models/areas');
module.exports = function (app) {
app.get("/", (req,res)=>{
areas.getAreas((err, data) => {
res.json([]);
});
});
}
try importing connection.js in areas.js,
maybe because never enter in that if statement, returns undefined

TypeError: Cannot read property 'BSON' of undefined

i'm deploying a nodeJS application with PM2, the process starts fine, but, when i try to access the URL, it stops the process, and then give me an "errored" status. Check the logs and i get this:
TypeError: Cannot read property 'BSON' of undefined
MyExpenses-0 (err): at Object.<anonymous>(/home/develop/development/nodejs/expenses/node_modules/mongodb/lib/mongodb/index.js:46:40)
MyExpenses-0 (err): at Module._compile (module.js:435:26)
MyExpenses-0 (err): at Object.Module._extensions..js (module.js:442:10)
MyExpenses-0 (err): at Module.load (module.js:356:32)
MyExpenses-0 (err): at Function.Module._load (module.js:311:12)
MyExpenses-0 (err): at Function._load (/usr/local/lib/node_modules/pm2/node_modules/pmx/lib/transaction.js:62:21)
MyExpenses-0 (err): at Module.require (module.js:366:17)
MyExpenses-0 (err): at require (module.js:385:17)
MyExpenses-0 (err): at Object.<anonymous> (/home/develop/development/nodejs/expenses/node_modules/mongoose/lib/utils.js:5:16)
MyExpenses-0 (err): at Module._compile (module.js:435:26)
I'm using mongoose for db.
Any clue on this?
Thanks!
UPDATE:
// server.js
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
// Database configuration
var db = require('./config/db');
// Connetion port
var port = process.env.PORT || 3500;
// Connect to our mongo db
mongoose.connect(db.url);
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride('X-HTTP-Method-Override'));
// Setting router file
require('./app/routes')(app);
// Start app on PORT
app.listen(port);
console.log('Server listening...');
exports = module.exports = app;
My only API url is this:
app.post('/api/expenses/create/', function (req, res) {
var name = req.body.name;
var amount = req.body.amount;
var userId = req.body.userId;
User.findOne({'_id': userId}, function (err, user) {
if (!err) {
var newExpense = Expense({
name: name,
amount: amount,
user_id: userId
});
newExpense.save(function (expenseErr) {
if (!expenseErr) {
res.status(200).json({'message': 'Gasto creado correctamente.', expense: newExpense});
} else {
res.status(400).json({'message': expenseErr});
}
});
} else {
res.status(400).json({'message': 'El usuario seleccionado no existe.'});
}
});
});

Categories

Resources