The courier stranded in the process of sending a request - express js mongodb

Help needed with postman request issue when condition is not met


    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( ()=> {
                        // Code here to handle successful signup 
                    }).catch( error => {
                        // Code to handle errors during saving
                    });
                }
                // Need help with handling result in front end
            });
        }
    });

    app.listen(3000);

Seeking guidance on stopping code execution at "then" or catch block for displaying results on the frontend, experiencing issues with postman requests unless specific condition is met.

Answer №1

One important consideration is avoiding passing JSON as a query argument to your API, as this is not recommended practice.
Additionally, make sure to account for possible edge cases and handle them with appropriate else statements in your code.

It appears that there is missing an else block following the if(response == null) statement. Make sure to also address any potential errors (err) in your conditions.

Try including print statements for userInfo.username and userInfo.password, and provide a screenshot if you continue to experience difficulties resolving the issue.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the procedure for incorporating JavaScript into my tic-tac-toe game's HTML and CSS?

I have created a simple Tic Tac Toe game using HTML and CSS. Although there is no embedded Javascript, I do reference a Javascript file for functionality. Can anyone provide me with the most straightforward Javascript code that will display an 'X&apos ...

`The header navigation is not responding to window resizing functionality`

I am currently developing a header navigation that consists of a logo on the left side, a profile icon on the right side, and some navigation links in the middle. A left slide menu has been implemented to trigger when the window width is less than 700px. ...

Display or conceal the nearest element that was clicked

http://jsfiddle.net/KevinOrin/xycCx/1/ jQuery('.happening-main-text .readmore').click(function() { jQuery('.divmore').toggle('slow'); return false; }); ...

Destroying the entire HTML content results in the invalidation of both the HEAD and BODY tags post-

Upon clicking a button, I execute a script that sends the entire HTML content of a webpage (everything within the <html> tags) to a CGI script for processing. However, when I attempt to replace the existing content with the manipulated result, I enc ...

Protractor's browser.wait function is not functioning properly when conducting tests on a non-AngularJS website

I am currently working on testing a non-angular JS website using Protractor. Even though my test case passes successfully, I am looking to eliminate the sleep statement and replace it with either a wait or Expected condition in my test case. Here is a sni ...

Modifying object colors on hover using three.js

As a beginner in the world of Three.js and WebGL, my first project involves creating a model of an animal and animating it in different ways, such as having its head follow the mouse cursor. The model consists of various geometries that are combined in sep ...

Executing a custom module that is installed globally on a Node server

After creating a custom module called "nawk" using npm, I am facing an issue while trying to run it as a command on my computer. Included in the package.json file: { "name": "nawk", "preferGlobal": true, "version": "0.0.1", "author": "My Name < ...

ExtJs rich text editor for text input

My attempt to insert a neatly formatted JSON string into my textarea field has been unsuccessful. I followed this method to format the string: How can I beautify JSON programmatically? and then simply used textarea.setValue(formattedJson); Take a look ...

The router.push function does not properly redirect to the specified path; instead, it just reloads the current page

I am a newcomer to NextJS and facing a challenge where I need to transfer data from the current page to another page. However, instead of loading the defined path in router.push as pathname: "/booking/checkout/", it loads the current page. I wan ...

Obtaining a dependency directly from the Injector within a directive

I am currently working on developing a versatile directive that can take a class type for validating rules. Depending on the rule specified in the class, the directive will either display or hide an element. This is my progress so far. Check out the PLUN ...

React application with a layout design that adjusts and responds to various

One task is to display various components based on the device's width; Two possible approaches have been considered: Create a React Component that accepts multiple components for different widths (sm, md, xl). It will automatically determine the de ...

Struggling to fetch data from the Strapi page is posing a challenge

Currently, I am facing an issue where the frontend developers on my team are unable to retrieve data from the backend that I built for them using Strapi. Even after pulling my changes from github, they continue to face difficulties accessing the data. The ...

"Displaying the y-axis in d3.js: A Step-by-Step

I am a beginner in d3.js and I'm having trouble with my y-axis not showing up in the browser. Can someone please help me find a solution? var barOffset=5; var barWidth=50; var width=700,height=700; function processData(data,key){ var objects=[]; ...

New example of how to use the "useSession" syntax in Next Auth

Currently, I am delving into the next-auth documentation and feeling perplexed by the syntax used in the useSession hook. The way it's showcased in the documentation is as follows: const { data: session, status } = useSession() My confusion stems f ...

Creating a URL in NodeJS/Express with multiple request query parameters

I am currently developing a small express API app that communicates with an external API. My goal is to construct the URL for the external API based on incoming query parameters to my API. I attempted to use an if/else statement, but encountered an issue w ...

Rotating a cone in three.js using two points and a specified radius

Using the coordinates and radius provided in an example XML file, I am trying to create a cone. Is there a way to rotate the cone if I have the top vertex's coordinates and the center of the base? Here is an image for reference: Image ...

Numerous modals implemented within a React component

Currently, I am working on mapping different products, each with its own "report" button. The issue I am facing is that when I click on the "report" button for one product, all the other modals also pop up showing irrelevant details. It should only display ...

Issue [ERR_REQUIRE_ESM]: Importing an ES Module using require() is not compatible with node_moduleswrap-ansiindex.js

Encountering an issue in my nestjs project with a library that is indirectly used by a third-party. stringWidth = require('string-width') in node_modules\wrap-ansi\index.js:2 not supported Here are the dependencies listed in package. ...

How can I effectively pass an array of objects to an interface in React with Typescript?

In my code, I have defined two interfaces as shown below: export interface TableBoxPropsHeader{ name: string, isIconOnly: boolean } export interface TableBoxProps<T> { headerNames: TableBoxPropsHeader[], // some stuff } I am currently fa ...

Text that is selected within a contenteditable div: Find the beginning and end points of the highlighted text

<div contenteditable="true">This text is <b>Bold</b> not <i>Italic</i> right?</div> For instance, if the text appears in a bold format, but not italic and the user selects it, how can I determine the exact position ...