Error : "TypeError:expressJwt not a function" [duplicate] - express-jwt

I'm trying to write middleware for user authorization in my app. I use this function to check if a route requires being sign in.
The code is as follows:
const { expressJwt } = require('express-jwt');
exports.requireSignin = expressJwt({
secret: process.env.JWT_SECRET,
algorithms: ["HS256"],
userProperty: "auth",});
However, I get the following error:
TypeError: expressJwt is not a function at Object.<anonymous> (path to the file)\
What could be the problem? None of the other answers seem to be helpful.

With the curly brackets
const { expressJwt } = require('express-jwt');
^ ^
you are trying to do object destructuring, which looks for a field named expressJwt in the object exported by express-jwt module. But according to the error message that object doesn't have such field.
As per express-jwt's documentation, you don't need destructuring but to simply assign the exported object into a variable, so try the following form (without curly brackets):
const expressJwt = require('express-jwt');

With version greater than 7.x, use this as doc said :
const { expressjwt: jwt } = require("express-jwt");

this work for me without high severity vulnerability caused by low version:
npm uninstall express-jwt
npm install express-jwt#6.1.0

Reference to the readme.
If I am not mistaken the right function is named jwt
//const { expressJwt } = require('express-jwt');
//use this
var jwt = require('express-jwt');

I tried all the possible solution found on multiple programming forums, but nothing worked, so I just downgrade my express-jwt version to 5.3.1 and it start working perfectly, so it means error is in new update, just uninstall current version with npm uninstall express-jwt and install again npm I express-jwt#5.3.1, it will help.

Following the documentation worked for me:
var { expressjwt: jwt } = require("express-jwt");
var jwtCheck = jwt({
secret: jwks.expressJwtSecret({
cache: true,
...more stuff
})

If you don't have an algorithm in the expressJwt object, add it next to the secret, separated by , and use cypher such as RS256. It happened to me.

Related

How to make Passport.js work in Adonis Framework

I wanted to know if Passport.js can ONLY be used in an Express framework and not in any other? The docs doesn't completely answer my question. I'm in the middle of migrating my project from Express to Adonis.js and I can't seem to make passport work. Here is a sample of my code:
const passport = use('passport')
const bearer = use('./bearer')
passport.use('bearer', bearer)
module.exports = passport
and here is how I register it:
const namedMiddleware = {
auth: 'Adonis/Middleware/Auth',
guest: 'Adonis/Middleware/AllowGuestOnly',
bearer: passport.authenticate(['bearer'], { session: false }),
}
this is the usage (I provided a bearer token):
Route.post('/', ({ response }) => {
response.json('Hello world')
}).middleware(['bearer'])
It does not work. Error about res.setHeader is not a function showing. Maybe because the resoponse and http structure is different in adonis?
I know that Adonis has its own authentication library but my INITIAL goal is to get what I have now in Express to work in an Adonis environment before making any library changes to avoid any complications.
I recently migrated from knex to adonis.js as well. Integrating passport.js was initially painful but I get it to work with Macros.
For your error, Adonis' Request object has no setHeader. You will need to create a macro on Request for that function. Something like this
function setHeader (name, value) {
this.header(name, value)
}
Response.macro('setHeader', setHeader)
Add that to a provider or hooks and you should be all set.

What does ".Strategy" do in Node or Passport?

What does ".Strategy" do here? Is it Node? Is it Passport?
var LocalStrategy = require('passport-local').Strategy;
Everything up to '.Strategy' part I understand. I just want to know what '.Strategy' does. I have checked the documentation on passport-local module on npm. I have also checked Passport's documentation, and it is just used in code snippets. No explanation is provided.
I am working with the MEAN stack and we are using Passport to authenticate users.
If you look at the sources of passport-local index.js you'll see it exports the same thing directly and in exports.Strategy.
When you do require('passport-local).Strategy you import the export defined in exports.Strategy, but it's really the same to do just require('passport-local') in this case because the same constructor is exported directly from the module.
If you define a module like this:
var Thing = { foo: () => 'bar' };
exports = module.exports = Thing;
exports.Thing = Thing;
you can use it in many ways:
const Thing = require('./module');
console.log(Thing.foo());
works, as does
const Thing = require('./module').Thing;
console.log(Thing.foo());
and with both imports you can actually call also
console.log(Thing.Thing.foo());
If you remove the exports.Thing = Thing; part of the module, then
const Thing = require('./module').Thing;
does not work anymore.
The exports cause confusion often. You could take a look of Node docs or eg. this answer.

Trying to Update Open API Spec from 2.0 to 3.0 But YAML Still Evaluates as 2.0.

I am trying to update my local swagger project from OpenAPI 2.0 to OpenAPI 3.0.
I am getting a ton of errors which imply that I my YAML file is still being evaluated as OAS2.0:
Project Errors
--------------
#/: Missing required property: swagger
#/: Additional properties not allowed: components,servers,openapi
#/paths/~1auth~1info~1firebase/get/responses/200: Not a valid response definition
#/paths/~1posts~1{id}~1comments/get/responses/200: Not a valid response definition
#/paths/~1posts~1{id}~1comments/get/parameters/2: Not a valid parameter definition
#/paths/~1posts~1{id}~1comments/get/parameters/1: Not a valid parameter definition
#/paths/~1posts~1{id}~1comments/get/parameters/0: Not a valid parameter definition
#/paths/~1users~1{id}~1profile/get/responses/200: Not a valid response definition
I have updated swagger-ui-express to the latest version.
Below are the relevant parts of my server.js file:
const YAML = require('yamljs');
const swaggerDocument = YAML.load('./api/swagger/swagger.yaml');
const SwaggerExpress = require('swagger-express-mw');
const swaggerUI = require('swagger-ui-express');
const api = express();
let swaggerConfig =
{
appRoot: __dirname
}
let swaggerOptions =
{
explorer: true
};
api.use('/api/v1/docs/endpoints',
swaggerUI.serve,
swaggerUI.setup(swaggerDocument, swaggerOptions)
);
SwaggerExpress.create(swaggerConfig, function(err, swaggerExpress) {
if (err) { throw err; }
// install middleware
swaggerExpress.register(api);
});
I have updated swagger-ui-express and swagger-express-mw to the latest versions.
But I am still getting the above errors.
I am thinking that the way forward may be to not use swagger-ui-express
and rework my code for swagger-ui but I see online that people seem to
get things working with that npm module.
Any ideas what I am doing wrong?

Node.js Express: BodyParser Syntax

Hi everyone i am new to node.js and express. i am just experimenting with various node.js code from various tutorials.
As per the official npm website correct syntax to use methodOverride is
// Be sure to place after the body parser if you want to accept the method
// override using a post parameter
app.use(express.bodyParser());
// Accepts a single argument, the name of the method override parameter,
// defaults to "_method"
app.use(require('express-method-override')('method_override_param_name'));
But when i used this, i got the following error
Error: Most middleware (like bodyParser) is no longer bundled with Express and
ust be installed separately. Please see https://github.com/senchalabs/connect#m
ddleware.
at Function.Object.defineProperty.get (E:\node_modules\npm\node_modules\exp
ess\lib\express.js:89:13)
As far as i researched app.use(express.bodyParser()) is deprecated. Express no longer includes the bodyParser middleware. So to my guess app.use(bodyParser()) is right and i altered my code like this
app.use(bodyParser());
app.use(require('express-method-override')('method_override_param_name'));
Below is my put functionality code
app.put('/user/:id', function(req, res){
console.log('Sha Put testing');
console.log(req.body);
//user.findByIdAndUpdate({email: req.params.id},
user.update({email: req.params.id},
{
email: req.body.email,
name: req.body.name,
age : req.body.age
},
function(err, docs){
if(err) res.json('Error here paiyaa -->' + err);
else
{
console.log(docs);
res.redirect('/user/'+req.body.email);
}
});
});
When i replace app.put with app.post it works fine. But my task is to achieve PUT functionality.As mentioned in express-method-override source, I have used hidden field with the name _method, which helps to override POST method, and facilitates PUT method.
My Edit form code is
<h1>Editing #{user.name}'s profile!</h1>
form(method="POST", action="/user/#{user._id}")
input(type="hidden", name="_method", value="PUT")
p Name:
input(type="text", name="name", value="#{user.name}")
p Age:
input(type="number", name="age", value="#{user.age}")
p
input(type="submit")
When i run the above code it throws below error while submitting the form
Cannot POST /user/test#gmail.com
Can some expert help me to fix this and understand bit clear please
You have a PUT route defined with app.put, but are trying to POST to it. The verbs need to match up, so either your request should be a PUT (makes sense for your user.update method) or change the route to app.post.
EDIT:
Looking at the source for express-method-override, your request body needs to have a _method: 'PUT' (as a default -- currently you are passing 'method_override_param_name' property on it in order for the middleware to override the POST verb.
If you are not already, you should also be including the body-parser middleware. npm install body-parser on the commandline or add it to your package.json and run npm install. var bodyParser = require('body-parser'); will then give the rest of your code what it needs to include the middleware.

Connect and Express utils

I'm new in the world of Node.js
According to this topic: What is Node.js' Connect, Express and “middleware”?
I learned that Connect was part of Express
I dug a little in the code, and I found two very interesting files :
./myProject/node_modules/express/lib/utils.js
and better :
./myProject/node_modules/express/node_modules/connect/lib/utils.js
These two files are full of useful functions and I was wondering how to invoke them correctly.
As far, in the ./myProject/app.js, that's what I do:
var express = require('express')
, resource = require('express-resource')
, mongoose = require('mongoose')
, expresstUtils =
require('./node_modules/express/lib/utils.js');
, connectUtils =
require('./node_modules/express/node_modules/connect/lib/utils.js');
But I found it a little clumsy, and what about my others files?
e.g., here is one of my routes:
myResources = app.resource(
'myresources',
require('./routes/myresources.js'));
and here is the content of myresources.js:
exports.index = function(req, res)
{
res.render('./myresources.jade', { title: 'My Resources' });
};
exports.show = function(req, res)
{
fonction resourceIsWellFormatted(param)
{
// Here is some code to determine whether the resource requested
// match with the required format or not
// return true if the format is ok
// return false if not
}
if (resourceIsWellFormatted(req.params['myresources']))
{
// render the resource
}
else
{
res.send(400); // HEY! what about the nice Connect.badRequest in its utils.js?
}
};
As you can see in the comment after the res.send(400), I ask myself if it is possible to use the badRequest function which is in the utils.js file of the Connect module.
What about the nice md5 function in the same file?
Do I have to place this hugly call at the start of my myresources.js to use them?:
var connectUtils =
require('../node_modules/express/node_modules/connect/lib/utils.js');
or, is there a more elegant solution (even for the app.js)?
Thank you in advance for your help!
the only more elegant way i came up with is (assuming express is inside your root "node_modules" folder):
require("express/node_modules/connect/lib/utils");
the node installation is on windows, node version 0.8.2
and a bit of extra information:
this way you don't need to know where you are in the path and be forced to use relative paths (./ or ../), this can be done on any file nesting level.
i put all my custom modules inside the root "node_modules" folder (i named my folder "custom_modules") and call them this way at any level of nesting:
require("custom_modules/mymodule/something")
If you want to access connect directly, I suggest you install connect as a dependency of your project, along with express. Then you can var utils = require('connect').utils.

Resources