简体   繁体   English

无法读取 undefined sequelize express JS 的属性“findAll”并且 req.body 是一个空对象

[英]Cannot read property 'findAll' of undefined sequelize express JS and req.body is an empty object

I'm having trouble taking the data from the table and creating an API.我无法从表中获取数据并创建 API。 The table isn't empty but req.body is and it says Vehicle is undefined ?该表不是空的,但 req.body 是并且它说 Vehicle is undefined ? The exact Error message I get is "TypeError: Cannot read property 'findAll' of undefined" and the req.body response is an empty object.我得到的确切错误消息是“TypeError:无法读取未定义的属性 'findAll'”,并且 req.body 响应是一个空对象。

Please help, I've tried everything.请帮忙,我已经尝试了一切。

Model:模型:

 import { Model } from 'sequelize'; const PROTECTED_ATTRIBUTES = ['password']; export default (sequelize, DataTypes) => { class Vehicles extends Model { toJSON() { // hide protected fields const attributes = { ...this.get() }; // eslint-disable-next-line no-restricted-syntax for (const a of PROTECTED_ATTRIBUTES) { delete attributes[a]; } return attributes; } /** * 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(vehicles) { // define association here } }; Vehicles.init({ // id: DataTypes.INTEGER, make: DataTypes.STRING, model: DataTypes.STRING, createdAt: DataTypes.DATE, updatedAt: DataTypes.DATE }, { sequelize, modelName: 'Vehicles', }); return Vehicles; };

Models/index.js:模型/index.js:

 import fs from 'fs'; import path from 'path'; import Sequelize from 'sequelize'; import enVariables from '../config/config.json'; const basename = path.basename(__filename); const env = process.env.NODE_ENV || 'development'; const config = enVariables[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 => (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js')) .forEach(file => { // eslint-disable-next-line global-require,import/no-dynamic-require const model = require(path.join(__dirname, file)).default(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; export default db;

Index.js:索引.js:

 const express = require('express'); const models = require('./src/models'); const Vehicles = models.Vehicles; const app = express(); var bodyParser = require('body-parser'); const jsonParser = bodyParser.json(); app.use(bodyParser.urlencoded({ extended: true })) app.use(bodyParser.json()) app.get('/', function(req, res){ res.send('Hello, please go to /vehicles !') }) app.get('/vehicles', jsonParser, async function(req ,res){ // res.send('page under construction') // console.log(Vehicles.findOne()) Vehicles.findAll().then(users => { return users }); }); const port = 5000; app.listen(port, () => { console.log('App is now running at port ', port) })

Issue has been solved, it is because I was using EcmaScript modules ( export , import ) in models/index.js , then importing it using CommonJS ( module.exports , require ) in index.js.问题已经解决,这是因为我在models/index.js中使用EcmaScript模块( exportimport ),然后在 index.js 中使用CommonJSmodule.exportsrequire )导入它。 That caused issues.这引起了问题。 I should have used the same module format on both sides, or console.log what require('./src/models') outputs to debug it.我应该在两边都使用相同的模块格式,或者console.log输出什么require('./src/models')来调试它。

I changed:我变了:

const models = require('./src/models')

To:至:

const models = require('./src/models').default;

but I ideally should only use one module format但理想情况下我应该只使用一种模块格式

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

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