Home > Software engineering >  MongoDB connect 400 error message on postman
MongoDB connect 400 error message on postman

Time:03-13

I'm new to mongoDB using Node. Unfortunately, I use postman and got 400 error, While connection to MongoDB. my env file is exist: DB_CONNECT = mongodb srv://Hadar:******@cluster.r5qw9.mongodb.net/User?retryWrites=true&w=majority Make sure the user and password both are correct.

enter image description here

const mongoose = require('mongoose')

const userSchema = new mongoose.Schema({
    name:{
        type: String,
        required: true,

    },
    password:{
        type:String,
        required:true,
    }
})

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

const express = require('express')
const app = express()
const mongoose = require('mongoose')
const dotenv = require('dotenv')
dotenv.config()
//connect to DB
mongoose.connect(process.env.DB_CONNECT,
() => console.log('connect to DB'))

app.use(express.json())

//import routes
const authRoutes = require('./routes/auth')

//Router Middlewares
app.use('/api/user',authRoutes)
app.listen(5000, ()=>{console.log('Server is up and running')})

const router = require('express').Router();
const User = require('../model/User')

router.post('/Login', async (req,res) =>{
    const user = new User({
        name: req.body.name,
        password: req.body.password
    });
    try{
        const savedUser = await user.save();
        res.send(savedUser);
    }catch(err){
        res.status(400).send(err);
    }
})

module.exports = router;

CodePudding user response:

router.post('/Login', async (req,res) =>{
  try{
    const user = new User({
      name: req.body.name,
      password: req.body.password
    });
    const savedUser = await user.save();
    res.send(savedUser);
  }catch(err){
    res.status(400).send(err);
  }
}

Change your code with above, problem can be related with trycatch block

CodePudding user response:

Solved! In postman: Content-Length : This header was present by default (along with 5 others) which I have disabled. Enable this and you'll receive the request body.

  • Related