【发布时间】:2021-09-22 18:48:00
【问题描述】:
当前从我的 notnull 验证器收到错误,但是我正在通过一个明显具有值的新对象传递定义的变量。用户、站点和联系人都是关联的,所以我不确定是否在我的 api 路由中,如果我不创建属性,那么只需从我的发布请求中传递它们,但是因为这是 MySql,我相信它是必需的,我可以肯定是错的。任何帮助或见解将不胜感激。
API 路由
console.log(req.body);
db.Case.create({
caseName: req.body.caseName,
userId: req.body.userId,
siteId: req.body.siteId,
contactId: req.body.contactId
}).then((response) => {
console.log(response);
res.json(response)
}).catch((err) => {
console.log(err);
})
})
型号
module.exports = (sequelize, DataTypes) => {
const Case = sequelize.define('Case', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
caseName: {
type: DataTypes.STRING,
allowNull: false,
},
createdAt: {
type: DataTypes.DATE
},
updatedAt: {
type: DataTypes.DATE,
},
})
Case.associate = (models) => {
Case.belongsTo(models.User, {
foreignKey : {
allowNull : false
}
})
Case.belongsTo(models.Site, {
foreignKey: {
allowNull: false
}
})
Case.belongsTo(models.Contact, {
foreignKey: {
allowNull : false
}
})
}
return Case;
}
发布请求
const caseName = $('#caseName');
const UserId = sessionStorage.getItem('id');
const SiteId = $('#insertSite').attr('id');
const ContactId = $('#insertContact').attr('id');
if(!caseName.val().trim() || !UserId || !SiteId || !ContactId){
console.log('Please enter all of the Case information')
return;
}
const newCase = {
caseName: caseName.val().trim(),
UserId: UserId,
SiteId: SiteId,
ContactId: ContactId,
};
console.log(newCase);
axios.post('/api/Case', newCase).then((res) => {
console.log('New Case has been added' + res);
}).catch((err) => {
console.log(err);
});
正在通过的测试对象
{
caseName: 'tttttttttt',
UserId: '1',
SiteId: 'insertSite',
ContactId: 'insertContact'
}
错误响应
errors: [
ValidationErrorItem {
message: 'Case.UserId cannot be null',
type: 'notNull Violation',
path: 'UserId',
value: null,
origin: 'CORE',
instance: [Case],
validatorKey: 'is_null',
validatorName: null,
validatorArgs: []
},
ValidationErrorItem {
message: 'Case.SiteId cannot be null',
type: 'notNull Violation',
path: 'SiteId',
value: null,
origin: 'CORE',
instance: [Case],
validatorKey: 'is_null',
validatorName: null,
validatorArgs: []
},
ValidationErrorItem {
message: 'Case.ContactId cannot be null',
type: 'notNull Violation',
path: 'ContactId',
value: null,
origin: 'CORE',
instance: [Case],
validatorKey: 'is_null',
validatorName: null,
validatorArgs: []
}
]
}
【问题讨论】:
标签: javascript mysql express sequelize.js