Harry Saliba
Harry Saliba

Reputation: 116

Node express middleware has undefined inputs

I'm new to Node.js and considering using it as an alternative to my current DOT NET API. Anyway, I wrote some middleware to require basic non-role authorization for my app and I keep getting compilation issues with my function inputs.

Compilation error:

harry@harry-pc:~/api.harry.technology$ npm start

> api.harry.technology@0.0.0 start /home/harry/api.harry.technology
> node ./bin/www

/home/harry/api.harry.technology/helpers/authorize.js:7
  if (req.get('Token')) {
          ^
TypeError: Cannot read property 'get' of undefined
    at module.exports (/home/harry/api.harry.technology/helpers/authorize.js:7:11)
    ...stack trace through library

helpers/authorize.js:

var express = require('express');
var config = require('../config.json');

module.exports = (req, res, next) => {
  // console.log(req.get('Token'));
  // The following line is line 7:
  if (req.get('Token')) {
    if (jwt.verify(token, config.secret)) {
      console.log(jwt.verify(token, config.secret));
      next();
    } else {
      return res.status(401).json({ message: 'Unauthorized' });
    }
  } else {
    return res.status(401).json({ message: 'Unauthorized' });
  }
}

routes/users.js:

var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var authorize = require('../helpers/authorize');

// (other routes)

/* POST user */
router.post('/', authorize, (req, res, next) => {
  connection.query(
    'INSERT INTO `users` (`username`, `firstname`, `lastname`, `phone`, `email`, `password`) VALUES (?, ?, ?, ?, ?, ?);',
    [req.body.username, req.body.firstname, req.body.lastname, req.body.phone, req.body.email, req.body.password],
    (error, results, fields) => {
      if (error) throw error;
      res.send(results);
    });
});

What I've tried:

I've seen similar issues around the web but the solutions either don't apply or don't work. I also read through sone JavaScript docs with no luck.

Upvotes: 0

Views: 362

Answers (2)

Roakz
Roakz

Reputation: 51

Good point by tksilicon above. But also it’s saying that req is undefined. Have you tried this without the middleware to make sure the request is coming through ? Or tried console logging the request itself out ?

Although we can’t see the server code it’s possible something else is going on with the request making it to the router.

Your router needs to be exported to the sever code and included as middleware in the server code so the request hits it.

Anyway some suggestions hope it helps

Upvotes: 1

tksilicon
tksilicon

Reputation: 4446

Use req.getHeader('token') Your should have sent the token in the header or use authorization header req.getHeader('authorization'); and strip out the bearer or better still use a standard middleware like passport.

See https://nodejs.org/api/http.html#http_request_getheader_name

Upvotes: 1

Related Questions