【发布时间】:2022-04-11 04:49:37
【问题描述】:
我正在从事一个社交网络项目。我正在用 postman 测试我的请求,但是当我在 postman 上测试我的 createPost 请求时出现问题,我收到错误。
我的邮递员请求:
{
"title": "Un titre",
"content": "un contenu",
"picture": "une image",
"usersId": 1
}
邮递员出错:
{
"error": {
"name": "SequelizeValidationError",
"errors": [
{
"message": "Post.UserId cannot be null",
"type": "notNull Violation",
"path": "UserId",
"value": null,
"origin": "CORE",
"instance": {
"id": null,
"title": "Un titre",
"content": "un contenu",
"picture": "une image",
"updatedAt": "2022-02-08T14:28:08.444Z",
"createdAt": "2022-02-08T14:28:08.444Z"
},
"validatorKey": "is_null",
"validatorName": null,
"validatorArgs": []
}
]
}
}
这是我的代码:
型号:
'use strict';
module.exports = (sequelize, DataTypes) => {
const Post = sequelize.define('Post', {
title: DataTypes.STRING,
content: DataTypes.STRING,
picture: DataTypes.STRING,
usersId: DataTypes.INTEGER
}, {});
Post.associate = function(models) {
models.Post.belongsTo(models.User, {
foreignKey: { //application clé étrangère posée sur la table
allowNull: false
}
});
};
return Post;
};
控制器:
const models = require('../models');
exports.createPost = (req, res, next) => {
let title = req.body.title;
let content = req.body.content;
let picture = req.body.picture;
let usersId = req.body.usersId;
models.Post.create({ title: title, content: content, picture: picture, usersId: usersId})
.then((response) =>{
res.status(201).json(JSON.stringify(response));
})
.catch((error) =>{
console.error(error);
res.status(400).json({ error })
})
.catch(error => res.status(500).json(error))
};
非常感谢您的帮助(我还是个初学者,肯定会有一些错误)。
【问题讨论】:
标签: sql express sequelize.js postman