I attempted to verify the login through postman, but encountered an error in the process

I created the login route on the backend and tested it in Postman, but encountered this error message: https://i.stack.imgur.com/PdyCo.png

Below is the code for the login route:

router.post("/login", async (req, res) => {
  try {
    const user = await User.findOne({email:req.body.email})
    if(!user){
      return res 
      .status(200)
      .send({message:"User does not exist",success:false})
    }
    const isMatch = await bcrypt.compare(req.body.password,user.password);
    if(!isMatch){
      return res
      .status(200)
      .send({message:"Password is incorrect",success:false})
    }
    else {
      const token = jwt.sign({id:user._id}, process.env.JWT_SECRET,{
        expiresIn: "1d"
      });
    }
    if(user && isMatch) {
          res.status(200).send({message:"Login successful",success:true,token,data:token});

    }
  } catch (error) {
    res
    .status(500)
    .send({message:"Error logging in",success:false,error})

  }
});

Answer №1

When working with else clauses to define a token variable in a local scope, it may not be accessible from the sending response scope. Here's an alternative approach:

try {
    const user = await User.findOne({ email: req.body.email });
    if (!user) {
      return res 
        .status(200)
        .send({ message: "User does not exist", success: false });
    }
    const isMatch = await bcrypt.compare(req.body.password, user.password);
    if (!isMatch) {
      return res
        .status(200)
        .send({ message: "Password is incorrect", success: false });
    } else {
      const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, {
        expiresIn: "1d"
      });
     
      res.status(200).send({ message: "Login successful", success: true, token, data: token });
    }
  } catch (error) {
    res
      .status(500)
      .send({ message: "Error logging in", success: false, error });
  }

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

The WhatsApp business API webhook is capable of sending out several responses at once

I am currently developing a WhatsApp Business API application that automatically responds to incoming messages by utilizing the data received from my API. However, I am encountering an issue where the app triggers multiple times after the initial message h ...

Tips for handling a local Mongo Database on an Android device

My goal is to develop an Android app that can function completely offline, allowing users to add new entries, view existing ones, delete and edit them without requiring internet access. For the backend, I plan to use nodejs with express and MongoDB. While ...

Efficiently caching and executing a function call in Node.js

My current project involves two NodeJS applications where one collects data from the other. I'm interested in finding a solution to automatically send this gathered data to a third application based on specific conditions. For instance, I would like ...

I have successfully implemented ngCordova local notifications, but now I am looking for a way to make it trigger for each individual

Is there a way to trigger a notification on every logged-in user's mobile device when a value is changed and saved in Firebase? Currently, I am able to send a local notification using ngCordova when a user enters text in an ionicPopup with textarea. H ...

Creating numerous bar graphs for each specific date

I have a dataset containing dates and corresponding information for each element. Despite trying various approaches, I am unable to create a barchart. Every solution I've attempted has been unsuccessful thus far. The dataset is structured as follows ...

Display identical text using JavaScript filter

My search filter highlight is currently displaying [object Object] instead of <mark>match values</mark> when replacing the values. This is the code I am using: this.countries.response.filter((val) => { const position = val.value.toLowerCa ...

create new Exception( "Invalid syntax, expression not recognized: " msg );

Can someone assist me in identifying the issue at hand? Error: There seems to be a syntax error, and the expression #save_property_#{result.id} is unrecognized. throw new Error( "Syntax error, unrecognized expression: " msg ); Here is the c ...

What's causing the show/hide feature to malfunction within the for loop in Vue.js?

I've encountered an issue with my for loop where the show/hide functionality doesn't seem to work despite everything else functioning properly. I've been trying to troubleshoot this problem without success. <div id="app"> <ul> ...

What is the best way to iterate through my array and display each value within my button element?

I have a challenge where I'm trying to iterate over an array named topics. This array contains the names of various people. Within my loop, my goal is to extract each name and insert it into a button as text. When I use console.log within my loop, I ...

When using Node.js, the rendering of the ejs file does not function properly until the directory name is updated from "view" to "views"

After encountering a persistent status code 500 error on every request when trying to access the profile.ejs file saved in the view folder, a simple solution was discovered. By renaming the folder from 'view' to 'views', everything sudd ...

Encountering difficulty in retrieving data from an unidentified JSON array using Javascript

Exploring the realm of Javascript and JSON, I find myself faced with a challenge - accessing values in an unnamed JSON array. Unfortunately, as this is not my JSON file, renaming the array is out of the question. Here's a snippet of the JSON Code: [ ...

Using Express.js to send a response while simultaneously executing a background task

When working with Express.js, I have a need to execute a task after sending a response. My main goal is to minimize the response time and send back the response immediately without waiting for the task results to be returned to the client. The task itself ...

The date-picker element cannot be selected by html2canvas

I'm encountering an issue with Html2canvas while trying to capture a screenshot of my page. Specifically, the date shown in the date-picker on the page is not appearing in the screenshot. Do you have any insights into why this might be happening and h ...

Leveraging variables from views.py in JavaScript

My approach to populating a user page has evolved. Initially, users would choose a value from a drop-down and an AJAX call would retrieve data. Here is the code that was functioning: HTML: <h3>Experimenter: {{ request.user }}</h3> <h3>R ...

What could be causing the "Undefned Jquery-ajax" error to pop up

I am struggling with the following code. My goal is to populate values into a dropdown <select> box, but I keep receiving an error of undefined. I have tried switching between Object.keys and Object.values, however, I am still facing the same issue. ...

Mongoose and Next.js: Encountered Runtime Error - Cannot Access Undefined Properties (Token)

For some reason, the Model I defined is not working properly, despite being similar to another one that works without errors. Can anyone help me figure out why? If you need to see a minimal, reproducible example, check it out here. The problematic code: ...

Unable to store cookie using jQuery on Internet Explorer 9

Having trouble setting a cookie on IE9 and can't figure out why. My objective is to create a cookie that expires after a year, using the code below: $.cookie( name, value, { expires:days } ) where days equals 365. However, the cookie disappears as s ...

What could be causing a functional component's child component to be using stale props?

I am currently working with Next JS, but the process is similar. I have refined the code and eliminated irrelevant parts. My goal is to create a form where new fields (child components) can be added dynamically. The default setting will be 1 field, with a ...

Display the QWebEngineView page only after the completion of a JavaScript script

I am currently in the process of developing a C++ Qt application that includes a web view functionality. My goal is to display a webpage (which I do not have control over and cannot modify) to the user only after running some JavaScript code on it. Despit ...

Utilizing an API endpoint within a POST request

I'm facing a bit of a roadblock here and struggling to figure out the best approach. I need to add a new video to my database, gathering most information from a view form but needing some keys from an API. Here's a simplified version of what I ha ...