繁体   English   中英

Node express 中间件有未定义的输入

[英]Node express middleware has undefined inputs

我是 Node.js 的新手,并考虑将其用作我当前 DOT NET API 的替代品。 无论如何,我编写了一些中间件来要求对我的应用程序进行基本的非角色授权,并且我的 function 输入不断出现编译问题。

编译错误:

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

助手/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' });
  }
}

路线/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);
    });
});

我试过的:

我在 web 周围看到过类似的问题,但解决方案要么不适用,要么不起作用。 我还通读了一些 JavaScript 文档,但没有运气。

使用 req.getHeader('token') 你应该已经在 header 中发送了令牌或使用授权 header req.getHeader('authorization'); 并去掉不记名或更好地使用像护照这样的标准中间件。

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

上面 tksilicon 的观点很好。 但它也说 req 是未定义的。 您是否在没有中间件的情况下尝试过此操作以确保请求通过? 或者尝试控制台记录请求本身?

虽然我们看不到服务器代码,但请求发送到路由器时可能发生了其他事情。

您的路由器需要导出到服务器代码并作为中间件包含在服务器代码中,以便请求命中它。

无论如何,一些建议希望它有所帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM