gpt4 book ai didi

javascript - 要求 sequilize 模块在某些快速应用程序文件中返回未定义

转载 作者:行者123 更新时间:2023-12-03 22:32:16 25 4
gpt4 key购买 nike

目标 - 在 util.js util.js 中的 userHandler 中为 express 应用中的一些 express 路由创建类似中间件的回调,由 express-generator 和 sequlize-cli 生成。
预计 - 用户模型在 util.js 中的路由和 userHandler 中成功使用。
结果 - 用户模型在登录路由中成功工作,但在 util.js 的 userHandler 中未定义。当要求模型完全获得 {} 时。要求似乎是正确的。
控制台错误

[nodemon] starting `node ./bin/www`
{}
Fri, 15 Jan 2021 14:54:42 GMT server:server Listening on port 8000
here
Fri, 15 Jan 2021 15:53:33 GMT server:server TypeError: Cannot read property 'findByPk' of undefined
at C:\Users\bpali\Desktop\authorization1\server\utils.js:40:27
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at async C:\Users\bpali\Desktop\authorization1\server\utils.js:12:5
GET /users/my-info 500 23.306 ms - 2
文件结构
File structure
实用程序.js
const jwt = require('jsonwebtoken');
var debug = require('debug')('server:server');
const secret = process.env.SECRET || SgxLbntQGfukf1yEAYZyzLBJKvop8Z2k6q1YG0wOHXZMgbVNhhsLaSIOB8Rkw9Pe4anRpTAE8h95RCwDYLjSsbJhpdZruVKzpzGgw1bnqCLLS1gAU1R1uChtRYDkSBOoZkFdnG3sRVLtJz63gqEQkq7owtaACYOXAd1fPOFkUgwgxammROY1NgpmUJR9YOwhVtcq5mTu;
const { User } = require('./models');
const models = require('./models');
console.log(models); // {} - ???

const verifyToken = async (token) => new Promise((resolve, reject) => jwt.verify(token, secret, (err, decoded) => err ? reject(err) : resolve(decoded)));
const signToken = async (payload, options = { expiresIn: '365d' }) => new Promise((resolve, reject) => jwt.sign(payload, secret, options, (err, token) => err ? reject(err) : resolve(token)));
const asyncErrorHandler = (asyncFn, ...args) => async (req, res, next) => {
try {
await asyncFn(req, res, next, ...args);
next();
} catch (e) {
debug(e);
res.status(500).send(e);
}
}
const userHandler = (allowedTypes) => asyncErrorHandler(async (req, res, next) => {
const autHeader = req.get('Authorization');
if (!autHeader) {
res.status(401).send('Unauthorized');
next('route');
}
const autSplit = autHeader.split && autHeader.split(' ');
if (!autSplit || autSplit.length !== 2 || !(autSplit[0] === 'Token' || autSplit[0] === 'Bearer')) {
res.status(401).send('Wrong format of authorisation');
next('route');
}
const token = autSplit[1];
console.log('here');
let decodedToken;
try {
decodedToken = await verifyToken(token);
} catch (e) {
res.status(403).send(`Wrong token! ${e.name + ': ' + e.message}`);
next('route');
}
const { login } = decodedToken;
const user = await User.findByPk(login);
if (!user) {
res.status(403).send('Wrong user');
next('route');
}
req.user = user;
if (allowedTypes && allowedTypes.indexOf && allowedTypes.indexOf(user.role) === -1) {
res.status(403).send('Not allowed role');
next('route');
}
next();
});

module.exports = { verifyToken, signToken, asyncErrorHandler, userHandler }
路线/users.js
var express = require('express');
var router = express.Router();
const { QueryTypes } = require('sequelize');
const { User, sequelize } = require('../models');
const { asyncErrorHandler, userHandler } = require('../utils');

/* GET users listing. */
// router.get('/', function(req, res, next) {
// res.send('respond with a resource');
// });

router.post('/login', asyncErrorHandler(async function (req, res, next) {
const { login, password } = req.body;
if (!login || !password || typeof login !== 'string' || typeof password !== 'string'){
res.status(400).send('Not empty login and password strings needed in json body');
next();
}
const user = await User.findByPk(login);
if (!user){
res.status(400).send('Absent login');
next('route');
}
if (!(await user.checkPassword(password))){
res.status(400).send('Wrong password');
next('route');
};
const { type } = user
res.json({
token: await user.makeToken(),
user: { login, type },
});
// next();
}));

router.post('/register', asyncErrorHandler(async function (req, res, next) {
const { login, password } = req.body;
if (!login || !password || typeof login !== 'string' || typeof password !== 'string'){
res.status(400).send('Not empty login and password strings needed in json body');
next('route');
}
if (await User.findByPk(login)) {
res.status(403).send('Busy login');
next('route');
}
const user = User.build({ login, type: 'user' });
await user.setPassword(password);
await user.save();
const { type } = user
res.json({ login, type });
// next();
}));

router.get('/my-info', userHandler(), function (req, res, next) {
const { login, type } = req.user;
res.json({ login, type });
});

router.get('/user-info/:login', userHandler(['admin']), asyncErrorHandler(async function (req, res, next) {
const user = await (User.findByPk(req.params.login));
if (!user) {
res.status(404).send('Login not found');
next('route');
}
const { login, type } = user;
req.json({ login, type });
// next();
}));

router.get('/list-users', userHandler(['admin']), asyncErrorHandler(async function (req, res, next) {
const users = await sequelize.query("SELECT * FROM `users`", { type: QueryTypes.SELECT });
console.log(users);
res.json(users);
}));

module.exports = router;
模型/index.js
'use strict';

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const db = {};

let sequelize;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
.readdirSync(__dirname)
.filter(file => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(file => {
const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
db[model.name] = model;
});

Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;
模型/user.js
'use strict';
const {
Model
} = require('sequelize');
const bcrypt = require('bcrypt');
const { signToken } = require('../utils');

module.exports = (sequelize, DataTypes) => {
class User extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
}
async setPassword (password) {
this.password = await bcrypt.hash(password, 10);
}
async checkPassword (password) {
return await bcrypt.compare(password, this.password);
}
async makeToken() {
const { login } = this;
return await signToken({ login });
}
};
User.init({
login: {
type: DataTypes.STRING,
primaryKey: true,
allowNull: false,
},
password: {
type: DataTypes.STRING,
allowNull: false,
},
type: {
type: DataTypes.STRING,
allowNull: false,
},
}, {
sequelize,
modelName: 'User',
});
return User;
};
app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};

// render the error page
res.status(err.status || 500);
res.render('error');
});

module.exports = app;
斌/www
#!/usr/bin/env node
require('dotenv').config()
/**
* Module dependencies.
*/

var app = require('../app');
var debug = require('debug')('server:server');
var http = require('http');

/**
* Get port from environment and store in Express.
*/

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
* Create HTTP server.
*/

var server = http.createServer(app);

/**
* Listen on provided port, on all network interfaces.
*/

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
* Normalize a port into a number, string, or false.
*/

function normalizePort(val) {
var port = parseInt(val, 10);

if (isNaN(port)) {
// named pipe
return val;
}

if (port >= 0) {
// port number
return port;
}

return false;
}

/**
* Event listener for HTTP server "error" event.
*/

function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}

var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;

// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}

/**
* Event listener for HTTP server "listening" event.
*/

function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
包.json
{
"name": "server",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www",
"dev": "nodemon ./bin/www"
},
"dependencies": {
"bcrypt": "^5.0.0",
"cookie-parser": "~1.4.4",
"debug": "~2.6.9",
"dotenv": "^8.2.0",
"express": "~4.16.1",
"hbs": "~4.0.4",
"http-errors": "~1.6.3",
"jsonwebtoken": "^8.5.1",
"morgan": "~1.9.1",
"pg": "^8.5.1",
"pg-hstore": "^2.3.3",
"sequelize": "^6.3.5"
},
"devDependencies": {
"nodemon": "^2.0.7"
}
}
.env
DEBUG=server:*
PORT=8000
SECRET=SgxLbntQGfukf1yEAYZyzLBJKvop8Z2k6q1YG0wOHXZMgbVNhhsLaSIOB8Rkw9Pe4anRpTAE8h95RCwDYLjSsbJhpdZruVKzpzGgw1bnqCLLS1gAU1R1uChtRYDkSBOoZkFdnG3sRVLtJz63gqEQkq7owtaACYOXAd1fPOFkUgwgxammROY1NgpmUJR9YOwhVtcq5mTu

最佳答案

发现问题 - 不明确的循环依赖
实用程序.js 需要 模型/index.js
模型/index.js 不直接需要 模型/user.js
模型/user.js 需要 实用程序.js ,更准确地说 - 签名 token 从中发挥作用
做了什么 - 更名 实用程序.js routeUtils.js , 把 签名 token 验证 token 函数到新文件 tokenUtils.js ,更新了其他文件中的导入,所以这种循环依赖不会发生,在此之后,它正确导入。
主要更新:
文件结构
File structure
routeUtils.js

// const jwt = require('jsonwebtoken');
var debug = require('debug')('server:server');
// const secret = process.env.SECRET || SgxLbntQGfukf1yEAYZyzLBJKvop8Z2k6q1YG0wOHXZMgbVNhhsLaSIOB8Rkw9Pe4anRpTAE8h95RCwDYLjSsbJhpdZruVKzpzGgw1bnqCLLS1gAU1R1uChtRYDkSBOoZkFdnG3sRVLtJz63gqEQkq7owtaACYOXAd1fPOFkUgwgxammROY1NgpmUJR9YOwhVtcq5mTu;
const { User } = require('./models');
const { verifyToken } = require('./tokenUtils');
// const models = require('./models');
// console.log(models); // {} - ???

// const verifyToken = async (token) => new Promise((resolve, reject) => jwt.verify(token, secret, (err, decoded) => err ? reject(err) : resolve(decoded)));
// const signToken = async (payload, options = { expiresIn: '365d' }) => new Promise((resolve, reject) => jwt.sign(payload, secret, options, (err, token) => err ? reject(err) : resolve(token)));
const asyncErrorHandler = (asyncFn, ...args) => async (req, res, next) => {
try {
await asyncFn(req, res, next, ...args);
// next();
} catch (e) {
debug(e);
res.status(500).send(e);
}
}
const userHandler = (allowedTypes) => asyncErrorHandler(async (req, res, next) => {
const autHeader = req.get('Authorization');
if (!autHeader) {
res.status(401).send('Unauthorized');
next('route');
}
const autSplit = autHeader.split && autHeader.split(' ');
if (!autSplit || autSplit.length !== 2 || !(autSplit[0] === 'Token' || autSplit[0] === 'Bearer')) {
res.status(401).send('Wrong format of authorisation');
next('route');
}
const token = autSplit[1];
// console.log('here');
let decodedToken;
try {
decodedToken = await verifyToken(token);
} catch (e) {
debug(e);
res.status(403).send(`Wrong token! ${e.name + ': ' + e.message}`);
next('route');
}
const { login } = decodedToken;
const user = await User.findByPk(login);
if (!user) {
res.status(403).send('Wrong user');
next('route');
}
req.user = user;
if (allowedTypes && allowedTypes.indexOf && allowedTypes.indexOf(user.type) === -1) {
// console.log('here');
res.status(403).send('Not allowed user type');
next('route');
}
next();
});

module.exports = { /* verifyToken, signToken, */ asyncErrorHandler, userHandler }
tokenUtils.js
const jwt = require('jsonwebtoken');
const secret = process.env.SECRET || SgxLbntQGfukf1yEAYZyzLBJKvop8Z2k6q1YG0wOHXZMgbVNhhsLaSIOB8Rkw9Pe4anRpTAE8h95RCwDYLjSsbJhpdZruVKzpzGgw1bnqCLLS1gAU1R1uChtRYDkSBOoZkFdnG3sRVLtJz63gqEQkq7owtaACYOXAd1fPOFkUgwgxammROY1NgpmUJR9YOwhVtcq5mTu;

const verifyToken = async (token) => new Promise((resolve, reject) => jwt.verify(token, secret, (err, decoded) => err ? reject(err) : resolve(decoded)));
const signToken = async (payload, options = { expiresIn: '365d' }) => new Promise((resolve, reject) => jwt.sign(payload, secret, options, (err, token) => err ? reject(err) : resolve(token)));

module.exports = { verifyToken, signToken };
模型/user.js
'use strict';
const {
Model
} = require('sequelize');
const bcrypt = require('bcrypt');
const { signToken } = require('../tokenUtils');

module.exports = (sequelize, DataTypes) => {
class User extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
}
async setPassword (password) {
this.password = await bcrypt.hash(password, 10);
}
async checkPassword (password) {
return await bcrypt.compare(password, this.password);
}
async makeToken() {
const { login } = this;
return await signToken({ login });
}
};
User.init({
login: {
type: DataTypes.STRING,
primaryKey: true,
allowNull: false,
},
password: {
type: DataTypes.STRING,
allowNull: false,
},
type: {
type: DataTypes.STRING,
allowNull: false,
},
}, {
sequelize,
modelName: 'User',
});
return User;
};

关于javascript - 要求 sequilize 模块在某些快速应用程序文件中返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65739305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com