Search code examples
node.jsexpresspassport.jsknex.js

Added passport authentication to an existing project and now get a Cannot read property of undefined error


I have a simple node/express/knex app that can read and edit a postgres db. I added passport authentication with auth0 and everything works beautifully. I was about to call it a day when I noticed I can't actually submit changes anymore. All the pages work that read from the database, but when I go to make a change and call a router.post route, I get an error like this. The weird thing is absolutely nothing has changed in that section of code. Happens in three separate routes.

TypeError: Cannot read property 'amp30' of undefined
   at /app/kml/index.js:431:22
   at Layer.handle [as handle_request] (/app/kml/node_modules/express/lib/router/layer.js:95:5)
   at next (/app/kml/node_modules/express/lib/router/route.js:131:13)
   at Route.dispatch (/app/kml/node_modules/express/lib/router/route.js:112:3)
   at Layer.handle [as handle_request] (/app/kml/node_modules/express/lib/router/layer.js:95:5)
   at /app/kml/node_modules/express/lib/router/index.js:277:22
   at Function.process_params (/app/kml/node_modules/express/lib/router/index.js:330:12)
   at next (/app/kml/node_modules/express/lib/router/index.js:271:10)
   at Function.handle (/app/kml/node_modules/express/lib/router/index.js:176:3)
   at router (/app/kml/node_modules/express/lib/router/index.js:46:12)
   at Layer.handle [as handle_request] (/app/kml/node_modules/express/lib/router/layer.js:95:5)
   at trim_prefix (/app/kml/node_modules/express/lib/router/index.js:312:13)
   at /app/kml/node_modules/express/lib/router/index.js:280:7
   at Function.process_params (/app/kml/node_modules/express/lib/router/index.js:330:12)
   at next (/app/kml/node_modules/express/lib/router/index.js:271:10)
   at SessionStrategy.strategy.pass (/app/kml/node_modules/passport/lib/middleware/authenticate.js:325:9)

Here is the entire route as an example.

router.post('/app/post/hydrant', function(req, res) {

  // Update hydrants based on data passed as POST to url/app/app-hydrants-single-edit-post
  knex('hydrants')
    .withSchema('snowmaking')
    .update({
      '30a': req.body.amp30,
      '60a': req.body.amp60,
      water: req.body.water,
      air: req.body.air,
      notes: req.body.notes,
      circuit: req.body.circuit,
      edit_by: req.body.edit_by
    })
    .where({
      id: req.body.id
    })
    .then(function(projectNames) {
      res.render('app-hydrants-single-edit-post');
    });

Solution

  • The issue could be because the body parser has not configured properly. To configure the body parser add the following code in your project(app.js)

    var app = express();
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({
        extended: false
    }));