gpt4 book ai didi

javascript - Node 应用程序无法识别 Sequelize 中间件代码

转载 作者:行者123 更新时间:2023-11-29 15:42:38 25 4
gpt4 key购买 nike

我是sequelize的新手,我创建了一个名为“db.js”的中间件,它连接到一个名为“users”的mysql表。每次我尝试运行 app.js 时,都会收到此错误:“TypeError:app.use() 需要中间件函数”。

但是,我有一个中间件功能。请参阅下面的代码:我错过了什么吗?我最后有 module.exports 对象。

我应该初始化sequelize吗?

db.js 文件

const Sequelize = require("sequelize");
const mysql = require("mysql");
const mysql2 = require("mysql2");

const db = {}
const sequelize = new Sequelize("smalldata", "root", "xxxx", {
host: "localhost",
dialect: "mysql",
operatorsAliases: false,

pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 90000
}
})

sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});

db.sequelize = sequelize
db.Sequelize = Sequelize

module.exports = db;

app.js 文件

const sequelize = require("sequelize");
const db = require("./middleware/db");
const express = require("express");

//Initialize Middleware
app.use(cors());
app.use(expressLayouts);
app.use(logger);
app.use(db);

user.js 文件

const Sequelize = require("sequelize");
const db = require("./db");

const User = db.sequelize.define(
'users',
{
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},

first_name: {
type: Sequelize.STRING
},

last_name: {
type: Sequelize.STRING
},

email: {
type: Sequelize.STRING
},

password: {
type: Sequelize.STRING
}
},

{
timestamps: true
},
)

// Note: using `force: true` will drop the table if it already exists
User.sync({ force: true }).then(() => {
// Now the `users` table in the database corresponds to the model
definition
return User.create({
first_name: 'John',
last_name: 'Hancock',
email:'johnhancock@gmail.com',
password:'johnny'
});
});

module.exports = User

最佳答案

我发现错误:app.js 文件中大写错误:const Sequelize = require("sequelize");

而不是:const Sequelize = require("sequelize");

关于javascript - Node 应用程序无法识别 Sequelize 中间件代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57439801/

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