javascript - Node express 中间件有未定义的输入
问题描述
我是 Node.js 的新手,并考虑将其用作我当前 DOT NET API 的替代方案。无论如何,我编写了一些中间件来要求对我的应用程序进行基本的非角色授权,并且我的函数输入不断出现编译问题。
编译错误:
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);
});
});
我试过的:
我在网上看到过类似的问题,但解决方案要么不适用,要么不起作用。我还通读了一些 JavaScript 文档,但没有运气。
解决方案
使用 req.getHeader('token') 你应该已经在标头中发送了令牌或使用授权标头 req.getHeader('authorization'); 并去掉不记名或更好地使用像护照这样的标准中间件。
见https://nodejs.org/api/http.html#http_request_getheader_name
推荐阅读
- python-3.x - TypeError:在尝试透视数据帧时未找到匹配的签名
- scala - IntelliJ View 错误描述在悬停时不显示
- c++ - C ++,Qt - 锁定保护和返回对对象的不可分配引用的安全性
- node.js - MongoDB 性能:用于并发读/写的单个集合与多个集合
- python - 为什么 optimize.curve_fit 不适用于较小的数据集?
- javascript - Angular Service 在延迟加载的模块中调用了两次
- google-app-engine - 如何部署需要定期访问大型数据文件的 Web 应用程序
- javascript - javascript画布。在全局组合操作之间切换
- javascript - JSON - 无法访问值
- javascript - 当提供一周中连续几天的字符串时,返回连接的星期几