Home > Blockchain >  CRUD implementation using ExpressJS with MySql ERROR : Cannot read properties of undefined (reading
CRUD implementation using ExpressJS with MySql ERROR : Cannot read properties of undefined (reading

Time:03-25

im trying to create a CRUD for my user, but i got a trouble when doing post request, i've seen some similar questions, but none are working for me

This is my userController

const { user } = require("../models");

  exports.all = (req, res) => {
    user.findAll().then((data) => {
        res.send(data);
    });
};

exports.findById = (req, res) => {
    user.findByPk(req.params.id).then((data) => {
        res.send(data);
    });
};

exports.create = (req, res) => {
    const newUser = {
        id: user.length,
        name: req.body.name,
        email: req.body.email,
        password: req.body.password,
        username: req.body.username,
        birth_date: req.body.birth_date,
        phone_number: req.body.phone_number,
        createdAt: new Date(),
        updatedAt: new Date(),
    };
    if (!newUser.name ||
        !newUser.email ||
        !newUser.password ||
        !newUser.username ||
        !newUser.birth_date ||
        !newUser.phone_number
    ) {
        return res.status(400).json({ msg: "Please fill all the requirements" });
    }
    user.create(newUser).then((data) => {
        res.send(data);
    });
};

exports.update = (req, res) => {
    const found = user.some((users) => users.id === parseInt(req.params.id));
    if (!found) {
        const updMmber = req.body;
        user.forEach((users) => {
            if (users.id === parseInt(req.params.id)) {
                users.name = updMmber.name ? updMmber.name : users.name;
                users.email = updMmber.email ? updMmber.email : users.email;
                users.password = updMmber.password ? updMmber.password : users.password;
                users.usersname = updMmber.usersname ?
                    updMmber.usersname :
                    users.usersname;
                users.birth_date = updMmber.birth_date ?
                    updMmber.birth_date :
                    users.birth_date;
                users.phone_number = updMmber.phone_number ?
                    updMmber.phone_number :
                    users.phone_number;
                res.send("Users Updated", user);
            }
        });
    } else {
        res
            .status(404)
            .json({ msg: `No user found with the id of  ${req.params.id}` });
    }
};

exports.delete = (req, res) => {
    const found = user.some((users) => id === parseInt(req.params.id));
    if (!found) {
        res
            .status(404)
            .json({ msg: `No user found with the id of  ${req.params.id}` });
    } else {
        res.json({
            msg: `User with id of ${req.params.id} has been deleted`,
            user: user.filter((users) => user.id !== parseInt(req.params.id)),
        });
    }
};

exports.update = (req, res) => {
    const found = user.some((users) => users.id === parseInt(req.params.id));
    if (!found) {
        const updMmber = req.body;
        user.forEach((users) => {
            if (users.id === parseInt(req.params.id)) {
                users.name = updMmber.name ? updMmber.name : users.name;
                users.email = updMmber.email ? updMmber.email : users.email;
                users.password = updMmber.password ? updMmber.password : users.password;
                users.usersname = updMmber.usersname ?
                    updMmber.usersname :
                    users.usersname;
                users.birth_date = updMmber.birth_date ?
                    updMmber.birth_date :
                    users.birth_date;
                users.phone_number = updMmber.phone_number ?
                    updMmber.phone_number :
                    users.phone_number;
                res.send("Users Updated", user);
            }
        });
    } else {
        res
            .status(404)
            .json({ msg: `No user found with the id of  ${req.params.id}` });
    }
};

exports.delete = (req, res) => {
    const found = user.some((users) => id === parseInt(req.params.id));
    if (!found) {
        res
            .status(404)
            .json({ msg: `No user found with the id of  ${req.params.id}` });
    } else {
        res.json({
            msg: `User with id of ${req.params.id} has been deleted`,
            user: user.filter((users) => user.id !== parseInt(req.params.id)),
        });
    }
};

This is my user model

"use strict";
const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
    class user 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
        }
    }
    user.init({
        name: DataTypes.STRING,
        email: DataTypes.STRING,
        password: DataTypes.STRING,
        username: DataTypes.STRING,
        birth_date: DataTypes.INTEGER,
        phone_number: DataTypes.STRING,
    }, {
        sequelize,
        modelName: "user",
    });
    return user;
};

This is my server.js

const express = require("express");
const app = express();
const PORT = 3000;
const userController = require("./controller/userController");
const addressesController = require("./controller/addressesController");

app.listen(PORT);

app.get("/", (req, res) => {
    res.send("Hello World");
});
//user routes
app.get("/user", userController.all); // show Alldata user
app.get("/user/:id", userController.findById); // show data user :id
app.post("/user", userController.create); // create data user
app.post("/user/:id"); //update data user :id
app.delete("/user/:id"); //delete data user :id

This is the response when im trying to do a post request in postman https://i.stack.imgur.com/vWnK5.png

Thank you so much for your help I really appreciate it!

CodePudding user response:

You need to pass in a middleware to parse JSON requests in Express.

In Express 4.16 , the express.json() middleware is available:

const app = express();

app.use(express.json()); // add this

// routes, etc...

In Express 4.0 - 4.15, use the body-parser package:

const app = express();
const bodyParser = require('body-parser');

app.use(bodyParser.json()); // add this

// routes, etc...

In Express <4:

const app = express();

app.use(express.bodyParser()); // add this

// routes, etc...
  • Related