Postman gets stuck on sending the request when I don't put res.status(200).json({message: "success", status: true});
outside the if statement
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 to stop the code on the "then" part or catch, I want to capture the result and display it on the frontend. Postman is stuck on sending the request when I don't put res.status(200).json({message: "success", status: true}); outside the if statement
P粉1017086232024-03-31 09:40:33
First of all, you are passing JSON as query parameters to the API, which is not a good idea.
And in your code you should consider and handle corner
conditions using else statements.
else
statement has no if(response == null)
statement. And also handles err
conditions.
Try adding print userInfo.username
and userInfo.password
and add a screenshot here if the issue is not resolved.