gpt4 book ai didi

node.js - 类型错误 : Cannot read property 'Tasks' of undefined

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

我是一个新手 Nodejs 编码员,并试图了解如何将 Sequelize ORM 与 Sqlite 一起使用。我创建了我的数据库并定义了所需的配置、路由、模型等。但是,当我在此帖子 URL http://127.0.0.1:3000/tasks 上测试来自 Postman 的 API 时,出现错误。

  var Tasks = app.db.models.Tasks;
^

TypeError: Cannot read property 'Tasks' of undefined
at Function.module.exports (C:\Users\Utku\Desktop\msi-nb\Git Clones\nodejs_projects\nodejs-sqlit3-sequelize\src\routes\/tasks.js:2:31)
at Consign.into (C:\Users\Utku\Desktop\msi-nb\Git Clones\nodejs_projects\nodejs-sqlit3-sequelize\node_modules\consign\lib\consign.js:240:17)
at Object.<anonymous> (C:\Users\Utku\Desktop\msi-nb\Git Clones\nodejs_projects\nodejs-sqlit3-sequelize\src\/index.js:17:4)
at Module._compile (internal/modules/cjs/loader.js:1137:30)
at Module._compile (C:\Users\Utku\Desktop\msi-nb\Git Clones\nodejs_projects\nodejs-sqlit3-sequelize\node_modules\pirates\lib\index.js:99:24)
at Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
at Object.newLoader [as .js] (C:\Users\Utku\Desktop\msi-nb\Git Clones\nodejs_projects\nodejs-sqlit3-sequelize\node_modules\pirates\lib\index.js:104:7)
at Module.load (internal/modules/cjs/loader.js:985:32)
at Function.Module._load (internal/modules/cjs/loader.js:878:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! nodejs-sqlit3-sequelize@1.0.0 babel-node: `babel-node src/index.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the nodejs-sqlit3-sequelize@1.0.0 babel-node script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
我已经在网上查看了解决方案。我没有使用 sequelize.import ,而是稍微更改了行并使用了 require() ,因为 import 已被弃用。检查了我需要的库和文件。我错过了什么?这是代码。
index.js
import express from "express";
import consign from "consign";

const app = express();

consign({
cwd: __dirname,
})
.include('libs/config.js')
.then('db.js')
.then("libs/middlewares.js")
.then('routes')
.then("libs/boot.js")
.into(app);
config.js
module.exports = {
database: "task",
username: "",
password: "",
params: {
dialect: "sqlite",
storage: "task-db.sqlite",
define: {
underscored: true,
},
operatorsAliases: false,
},
};
db.js
import Sequelize from "sequelize";
import path from "path";
import fs from "fs";
const sqlite = require("sqlite3");

// let db = null;
let db = new sqlite.Database("task-db.sqlite");

module.exports = (app) => {
if (!db) {
const config = app.libs.config;

const sequelize = new Sequelize(
config.database,
config.username,
config.password,
config.params
);

db = {
sequelize,
Sequelize,
// app.db.models.Tasks
// app.db.models.Users
models: {},
};

// let modules = [require("./models/users"), require("./models/tasks")];

const dir = path.join(__dirname, "models");
fs.readdirSync(dir).forEach((filename) => {
const modelDir = path.join(dir, filename);
const model = require(modelDir);
// const model = sequelize.import(modelDir);
db.models[model.name] = model;
});

// // Initialize models
// modules.forEach((module) => {
// const model = module(db.sequelize, db.Sequelize, config);
// db.models[model.name] = model;
// });

Object.keys(db.models).forEach((key) => {
if (db.models[key].hasOwnProperty("associate")) {
db.models[key].associate(db.models);
}
});
}

return db;
};
中间件.js
import express from 'express';

module.exports = app => {
// Settings
app.set('port', process.env.PORT || 3000);
app.set('json spaces', 4);

// Middlewares
app.use(express.json());
app.use((req, res, next) => {
// Delete req.body.id;
next();
});

};
tasks.js
module.exports = (app) => {
const Tasks = app.db.models.Tasks;

app
.route("/tasks")
.get((req, res) => {
Tasks.findAll({})
.then((result) => res.json(result))
.catch((error) => {
res.status(412).json({ msg: error.message });
});
})
.post((req, res) => {
console.log(req.body);
// To test post request
// res.json({ status: "received" });

Tasks.create(req.body)
.then((result) => res.json(result))
.catch((error) => {
res.status(412).json({ msg: error.message });
});
});
};
boot.js
module.exports = app => {
app.db.sequelize.sync(() => {
app.listen(app.get('port'), () => {
console.log('Server on port', app.get('port'));
});
});
};
tasks.js(模型)
module.exports = (sequelize, DataType) => {
const Tasks = sequelize.define("Tasks", {
id: {
type: DataType.INTEGER,
primaryKey: true,
autoIncrement: true,
},
title: {
type: DataType.STRING,
allowNull: false,
validate: {
notEmpty: true,
},
},
done: {
type: DataType.BOOLEAN,
allowNull: false,
defaultValue: false,
},
});

Tasks.associate = (models) => {
Tasks.belongsTo(models.Users);
};

return Tasks;
};
文件夹结构
enter image description here

最佳答案

如果 tasks.js 中模型的名称是 task ,则应使用 app.db.models.task 。如果你的模型名称是 Task 你应该使用 app.db.models.Task

关于node.js - 类型错误 : Cannot read property 'Tasks' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63658508/

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