0

While this one works perfect with postman get "welcome message" and post /login request, gives no error nor saves data in mongo cloud, but shows could not get response in POSTMAN

index.js file

const express = require("express");
const app = express();
const dotenv = require("dotenv");
const mongoose = require("mongoose");

// Import Routes
const authRoute = require("./routes/auth");

dotenv.config();

//Connect To DB
mongoose.connect(process.env.DB_CONNECT,
{ useNewUrlParser: true, useUnifiedTopology: true },
() => console.log("connected to DB")
);

//Middleware
app.use(express.json());

//Route Middleware
app.use("/api/user", authRoute);

app.listen(3000, () => console.log("Server up and running on port 3000"));

User Schema - User.js

const mongoose = require("mongoose");

const UserSchema = new mongoose.Schema({
    name : {
        type: String,
        required: true,
        min: 6,
        max: 50
    },
    email: {
        type: String,
        required: true,
        min: 6,
        max: 25
    }
    ,
    password: {
        type: String,
        required: true,
        min: 6,
        max: 1024
    },
    date:{
        type: Date,
        default: Date.now
    }
});
module.exports = mongoose.model("User", UserSchema);

auth.js file

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

router.post("/register", async (req, res) => {
  const user = new User({
    name : req.body.name,
    email: req.body.email,
    password: req.body.password
  });
  console.log("Entering Try Catch");
  try {
    console.log(user.name +" - " + user.email);
      const savedUser = await user.save();
      console.log("saved user = " + savedUser);
      res.send(savedUser);
  } catch (err) {
    console.log(err);
    res.status(400).send(err);
  }
});

router.get("/", (req, res) => {
  res.send("Welcome");
});

router.post("/login", (req, res) => {
  console.log("Console Logged In");
  res.send("Logged In Successful");
});

module.exports = router;

It would be of great help, if you could let me know where i'm mistaking. Thanks In Advance !!

Edit : i'm getting all the console till, Entering try catch as well as user.name and user.email

Hitesh
  • 109
  • 7

3 Answers3

1

Thanks everyone for your help, well it was not mistake in code or any other error for this one particular what i found is pretty strange, on atlas i allowed access to my current IP address despite that it still had this error now after changing it to Allow Access to all it is working, so i guess it should be the issue from mongo side that they should consider few rare incident like this.

Hitesh
  • 109
  • 7
0

hint: first of all, you should always use return for your responses.

try this :

  try {
    const user = await User.create({
        name : req.body.name,
        email: req.body.email,
        password: req.body.password
    });
    return res.send(user);
  } catch (err) {
    return res.status(400).send(err);
  }
});
Babak Abadkheir
  • 2,222
  • 1
  • 19
  • 46
0

You might want to install body-parser middleware for express in order to get the values from req.body

A good way to debug is console.log(req.body) and see if is undefined

Detailed answer here: What does body-parser do with express?

EDIT:

Most likely something with your database connection is the problem, because I'm using your code (copy/paste) and everything works fine for me.

You could add mongoose.connection.on('error', err => { console.log(err); }); below your mongoose.connect inside your index.js to debug your mongoose connection, you should wait around 30s-1min after making POST request.

index.js

And here is my .env file : DB_CONNECT=mongodb://localhost:27017/test

auth.js

Paul Şular
  • 145
  • 1
  • 10
  • 1
    ``` //Middleware app.use(express.json()); ``` this does the job – Hitesh Oct 12 '20 at 08:52
  • 1
    I edited my answer, does it help to debug? I expect the problem to be at the connection level – Paul Şular Oct 13 '20 at 08:17
  • Sular : Thank You very much for the help, but one thing which is out of my mind is that i went to mongo atlas created a cluster and copied the url from there which is present in DB_CONNECT. Now i'm wondering what could have gone wrong. BTW it works fine on local machine – Hitesh Oct 13 '20 at 09:37
  • Hi Paul, could you please point out what could be the issue here as i copied the exact uri from cluster connection, also with the same uri i'm getting a console message as **connected to DB** where as the same thing gives could not get response when sending a GET or POST request – Hitesh Oct 14 '20 at 02:55