req.body undefined for Post register User

Viewed 23

I'm trying to register use with Post endpoint req.body is undefined and I don't know why because endpoints for products work ok. model of User

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  login: { type: String, require: true },
  password: { type: String, require: true },
});

module.exports = mongoose.model('User', userSchema);

register endpoint

exports.register = async (req, res) => {
  try {
    const { login, password } = sanitize(req.body);
    console.log(req.body);
    const isLogin = login && typeof login === 'string';
    const isPassword = password && typeof password === 'string';
    const isDataValid = isLogin && isPassword;

    if (isDataValid) {
      const userWithLogin = await User.findOne({ login });
      if (userWithLogin) {
        return res
          .status(409)
          .json({ message: 'User with this login already exists' });
      }
      const user = new User({
        login,
        password: await bcrypt.hash(password, 10),
      });
      await user.save();
      res.status(201).json({ message: 'User created ' + user.login });
    } else {
      res.status(400).json({ message: 'Bad request' });
    }
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

using app.use(bodyParser.urlencoded({ extended: false })); doesn't I'm using app.use(express.urlencoded({ extended: false }));

Could you help me find an error?

1 Answers

if you are using express you have to give permission to use json , following code might work

const express = require("express");
const app = express.app();

app.use(express.json());    //this two line must be included for parsing data in body 
app.use(express.urlencoded({ extended: false }));

app.get("/", (req, res) => {
    res.json(req.body)     // this will send data of req.body
});

Related