0

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).

Oumar MAURET
  • 45
  • 1
  • 7
  • [follow the below link to get user_id](https://stackoverflow.com/questions/56753929/how-to-get-user-id-using-jwt-token) – Darshit Apr 12 '22 at 12:49

1 Answers1

0

I don't understand from where you "pushing" the userIdFound on your where clause in the querie.

But I think you can try to insert the value id in a const, and use him on the where. Supposing the id field name in your HTML sending the post or get request is "id", you can insert it like this:

const userIdFound = req.body.id;
await User.findOne({ where: { id: userIdFound } })
//Some code for the logic

You can see more in the documentation here