var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var multer = require('multer');
var upload = multer();
var cookieParser = require('cookie-parser');
var mongoose = require('mongoose');
app.set('view engine', 'pug');
app.set('views', 'views');
app.use(express.json());
app.use(bodyParser.json( { extended: true} ));
app.use(bodyParser.urlencoded({extended: true }));
app.use(upload.array());
app.use(cookieParser());
mongoose.set('strictQuery', true);
mongoose.connect('mongodb://127.0.0.1:27017/my_db',
{
useNewUrlParser: true,
useUnifiedTopology: true
},(err) => {
if(err){
}else{
console.log("connected");
}
}
);
var userSchema = mongoose.Schema({
username: {type: String, required: true, index: { unique: true }},
password: {type: String, required: true}
});
var User = mongoose.model("User", userSchema);
app.post('/signup', (req, res) => {
var userInfo = req.query;
if(!userInfo.username || !userInfo.password ){
res.status("400");
res.send("Invalid Details");
}else {
const newUser = new User({
username: userInfo.username,
password: userInfo.password
});
User.findOne({username: userInfo.username} , (err, response) => {
if(response == null){
newUser.save().then( ()=> {
res.status(200).json({ message: 'Success!', status: true});
// res.status(200).end();
}).catch( error => {
res.status(400).json({message: err, status: false});
console.log("existing user");
});
}
//res.status(200).json({message: "success", status: true});
});
}
});
app.listen(3000);
How do I stop the code on the "then" part or catch, I wanted to catch the result and display it on front end. postman stuck at sending request when im not putting res.status(200).json({message: "success", status: true}); outside the if statement
First thing is you are passing JSON as query argument to your API which is not a good idea.
And in the code, you should consider and handle the corner
conditions with the else statements.
There's no else
block to if(response == null)
statement. And also handle the err
conditions.
Try adding printing the userInfo.username
and userInfo.password
and add the screenshot here if the issue is not resolved.