Access + authentication code

After successfully using my login script in Postman, I ran into issues when attempting to integrate it with React.js for posting to the server.

The problem lies in the fact that when the script checks for the user, it fails to return the return result. It seems like nothing is happening at all.

Login route:

router.post('/login', async (req,res) => {
    console.error(req.body.password)
    try {
        var check = await checkUser(req.body.email, req.body.password).catch((result) => {
            console.log(result)
        })
    } catch(err){
        console.error(err)
    }
});

Check function:

async function checkUser(username, password) {
    var username = username;
    var password = password;
    var result;
  
    await Users.findOne({email: username}, async function (err, docs) { 
    // console.error(docs);
    if (err) { 
        console.log(err) 
    } else { 
        const match = await bcrypt.compare(password, docs.password);

        if(match) {
            result = {userid:docs._id, success:"true"}
            //result['userid'] = docs._id;
            //result['success'] = true;
        } else{
            result = {success:"false"}
            // result['success'] = false;
        }     
    }
    // console.error(result);
    return result;  
  })
}

I'm curious if anyone can pinpoint where I might be making a mistake.

Answer №1

Avoid using .catch() in conjunction with async / await. Instead, handle errors with try / catch.

router.post('/login', async (req,res) => {
    console.error(req.body.password)
    try {
        var check = await checkUser(req.body.email, req.body.password)
    } catch(err){
        console.error(err)
    }
});

Another issue arises when mixing callback functions with async / await. You are not getting any return values because the result is being passed to the callback function within an ...async function()...

Therefore, it's best practice to avoid combining callback functions with async / await.

Remember to choose either: async / await, chaining .then() .catch(), or utilizing callback functions individually. Mixing them can introduce unnecessary bugs.

async function checkUser(username, password) {
  var username = username;
  var password = password;
  var result;
  try {
    let user = await Users.findOne({ email: username });
    if (!user) return "no user found";

    const match = await bcrypt.compare(password, user.password);
    if (match) {
      result = { userid: user._id, success: "true" };
    } else {
      result = { success: "false" };
    }
    return result;
  } catch (err) {
    console.log(err);
  }
}

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

Tips for syncing input field values with mui slider?

Implementing a MUI slider that ranges from a minimum of 8 to a maximum of 255. <Slider value={range} min={minVal} max={maxVal} onChange={handleSliderChange} valueLabelDisplay="auto" /> In addition, displaying input fields to show ...

Is there a way to display the contents of a zipped file using an HTML IFrame?

Can I display the contents of a zipped file in an HTML iframe? For example: My_File.pdf.zip contains My_File.pdf. I currently have something like this <iframe src="/path of the folder/My_File.pdf.zip" /> The src attribute points to the zipped file ...

Deactivating the idle timer in React Native: A Step-by-Step Guide

Currently, I am working on an app that involves a timer using RN. However, I have noticed that after approximately 1 minute and 50 seconds, the device's screen starts to dim in preparation for sleep mode. ...

In Node.js, fast-xml-parse is only returning a single object instead of an array

Currently, I am working on implementing tracking functionality using a specific service that provides responses in XML format. For parsing the XML response, I have opted to utilize the fast-xml-parser package. However, I have encountered an issue: Everyth ...

Every time I attempt to execute route.js in my API folder, I encounter a persistent 404 error

Project Structure: https://i.stack.imgur.com/qMF6T.png While working on my project, I encountered an issue with a component that is supposed to call an API function. However, it seems like the file is not being found. I have double-checked the directory ...

Determining the Nearest Date in an Array Using JavaScript

In my array, I store information about each day as an object. For example: {day_year: "2012", day_month: "08", day_number: "03", day_name: "mon"} To enhance the day objects, I have included a timestamp attribute using the following function: function co ...

Important notice: Warning for stand-alone React 18 page regarding the import of createRoot from "react-dom"

I am in the process of developing a standalone webpage utilizing React 18: <!DOCTYPE html> <html lang="en"> <head> <title>Hello React!</title> <script crossorigin src="https://unpkg.com/react@1 ...

Choose an option with JavaScript once the request is successful

Choose the day, month, and year using JSON data success: function(jsondata){ var data=JSON.parse(jsondata); var list_html="<div id='editrelation'><label id='dateLabel' style='display:none&apo ...

Delay reading body until npm request completes

My current challenge involves using npm request and cheerio to extract webpages and analyze their HTML structure. Everything works smoothly in scenarios where the HTML is available upon request. However, I am facing a problem when a website initially displ ...

Checking the availability of a username by sending an Ajax request every time the user types it may lead to inefficiencies and slower response times. Are there

I have developed a NodeJS authentication application. In this scenario, when a user enters a username, the system will display "username taken" if it is already in use, otherwise it will show "username available". I am interested in understanding the lim ...

Discovering and editing a specific line in Sheets: An in-depth look at the Message Counter

Currently, the bot checks if your ID already exists in the sheet list and adds you if it doesn't when someone writes a message in the chat. Now, I want the bot to implement a message counter in the sheet list. What would be the most effective way to ...

Transmitting an Array Using an Ajax Call

Is there anyone knowledgeable in Ajax here? I'm struggling with sending a javascript array in an ajax request. Can someone provide me with an example of how the ajax request should be formatted? My goal is to gather all the javascript data, package it ...

Next.js Dynamic Routing: Navigating Your Website with Ease

Currently, I am developing an E-commerce website and implementing dynamic routing in Next.js. I am facing an issue where the route redirects to the category page, but when I click on any specific category, it shows a 404 error page because the route looks ...

Discover the versions of key libraries/modules within the webpack bundle

Is it possible to identify all the libraries, scripts, or modules included in a webpack bundle through the developer's console of a website that is already running, without access to its codebase? Additionally, is there a way to determine the version ...

Using NodeJS and Moongose to efficiently assign properties from req.body in bulk

Is there a way to streamline the process of assigning req.body properties to a newly created record, especially when dealing with a model that has a large number of properties? For example: var task = new Task(); task.title = req.body.title; task.desc = ...

Is it possible to create a component in React without using JSX?

Is it possible to create a React component without using JSX? I'm trying to render a header element with nested h1 and h2 tags, but only the paragraph tag is showing up. Why is only the React element rendering and not the rest? I referred to a Codepe ...

Discovering the method to extract a Specific Form Field value with JQuery

Recently, I encountered a form that looked like this: <form id="post_comment" action="cmt.php" method="post"> <input type="hidden" name="type" value="sub" /> <textarea id="body"></textarea> </form> To interact with the ...

Leveraging Express.js alongside websockets

I am currently working on an application that is built on Expressjs and Angularjs. I am looking to incorporate a few two-way calls in addition to the existing HTTP calls. While I have gone through some websocket chat tutorials, none of them seem to be inte ...

Parallax Effect Slows Down When Scrolling In Web Page

Currently in the process of creating a website with a scrolling parallax effect using Stellar.js on the header and three other sections. However, I'm experiencing lag when scrolling, especially at the top of the page. I've attempted to reduce la ...

I struggle with generating a transition effect in the input box through label transformation

Why is the input box not using the specified CSS styles for the input and label tags? The transform property doesn't seem to be working as expected. I've highlighted the areas where I'm facing issues with bold text, and I've included bo ...