My postman request :
{
"content": "my content",
"likes": 0
}
Response in postman :
{
null
}
Here is my code:
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class Post extends Model {
/**
* 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(models) {
// define association here
models.Post.belongsTo(models.User, {
foreignKey: {
allowNull: false,
name: "userId"
}
})
}
};
Post.init({
content: DataTypes.STRING,
comments: DataTypes.STRING,
attachment: DataTypes.STRING,
likes: DataTypes.INTEGER
}, {
sequelize,
modelName: 'Post',
});
return Post;
};
controllers :
module.exports.createPost = async (req, res, next) => {
const token = req.cookies.jwt;
const decoded = jwtAuth.verify(token, process.env.TOKEN_SECRET);
console.log(decoded);
const userIdFound = await User.findByPk(decoded.id);
I can't get the user id despite the request it returns a null value :
try {
const { body } = req;
console.log(body);
await User.findOne({ where: { id: userIdFound } })
.then((userFound) => {
//Create a Post if User Id is valid
if (userFound) {
const newPost = Post.create(
{ ...body, userId }
).then(() => res.status(201).json(newPost))
.catch(err => res.status(404).json('Unauthorizated request !'))
}})
Les erreurs :
} catch (err) {
throw new Error(err);
}
}
thank you very much for your help (I'm still a beginner, there will surely be some mistakes).