Postman issue: Your username and password combination is incorrect within the MEAN stack environment

I am new to mean stack development and facing some issues. When I try to run "api/users/login" in Postman, it shows an error saying "Username or password is invalid!". Additionally, when attempting to register using "register/users/register", it gives a message stating "user is already exist". How can I resolve these problems?

Here is my code :

user.router.ts

import {Router} from 'express';
import { sample_users } from '../data';
import jwt from 'jsonwebtoken';
import asyncHandler from 'express-async-handler';
import { User, UserModel } from '../models/user.model';
import { HTTP_BAD_REQUEST } from '../constants/http_status';
import bcrypt from 'bcryptjs';
const router = Router();

// Routes for seeding data

router.get("/seed", asyncHandler(
  async (req, res) => {
     const usersCount = await UserModel.countDocuments();
     if(usersCount > 0){
       res.send("Seed is already done!");
       return;
     }
 
     await UserModel.create(sample_users);
     res.send("Seed Is Done!");
 }
 ))

// Route for user login

router.post("/login", asyncHandler(
  async (req, res) => {
    const {email, password} = await req.body;

    // Check if the user exists and validate the password
    
  }
))

// Route for user registration

router.post('/register', asyncHandler(
  async (req, res) => {
    
  }
))

  export default router;

user.service.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { BehaviorSubject, Observable, tap } from 'rxjs';
import { USER_LOGIN_URL, USER_REGISTER_URL } from '../shared/constants/urls';
import { IUserLogin } from '../shared/interfaces/IUserLogin';
import { IUserRegister } from '../shared/interfaces/IUserRegister';
import { User } from '../shared/models/User';

@Injectable({
  providedIn: 'root'
})
export class UserService {

  // Methods for user login, registration, and logout

}

login.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { UserService } from 'src/app/services/user.service';

@Component({
  selector: 'app-login-page',
  templateUrl: './login-page.component.html',
  styleUrls: ['./login-page.component.css']
})
export class LoginPageComponent implements OnInit {

  // Login form component
  
}

auth.guard.ts

import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { UserService } from 'src/app/services/user.service';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  
  // Guard to check authentication status
  
}

Answer №1

After encountering a similar issue, I discovered that the solution was as simple as changing the Body to x-www-form-urlencoded in Postman - my code was actually fine all along.

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

Data is stored in the database without the need to fetch it through the $_POST method

Can someone explain how the variables are being inserted into the database without using $_POST to retrieve them? Is this a new feature in php5 or am I just unfamiliar with this method? <!doctype html> <html> <head> <title>< ...

redis-server.service could not be restarted as it was not found

Attempted to initiate redis-server but encountered the following error message: 26195:C 27 Aug 17:05:11.684 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf 26195:M ...

npm malfunctions following recent update

After updating npm with the command npm install -g npm@latest, I encountered an error when running any npm command, including npm --version. The error message reads: ERROR: npm v10.2.4 is known not to run on Node.js v14.15.4. This version of npm supports t ...

Error message saying 'Callback has already been invoked' returned by an async waterfall function

I'm facing an error that I understand the reason for, but I'm unsure how to resolve it. Here's a breakdown of my initial function: Essentially, I am making a get request for all URLs stored in the database and then, for each URL response, I ...

Create a ReactJS page with no pre-generated additional pages

Just ventured into the world of reactjs and created my first app. Now I'm trying to build a production version using the command: npm run build However, all I get is a blank index.html file generated. Why is this happening? I have multiple routes in ...

Automatically select the unique item from the list with Angular Material AutoComplete

Our list of document numbers is completely unique, with no duplicates included. I am attempting to implement a feature in Angular Material that automatically selects the unique entry when it is copied and pasted. https://i.stack.imgur.com/70thi.png Curr ...

Using a structural directive in Angular 2 that accepts a String as an input

I am attempting to develop a custom structural directive using the example provided here When trying to pass a string as an input with a slight modification, I encountered an issue where the input value was returning 'undefined' when calling th ...

Is there a way to trigger a function upon the loading of a template in Angular 2?

I'm a newcomer to angular2 and I need to trigger a function when a template loads or initializes. I have experience with achieving this in angular1.x, but I'm struggling to figure out how to do it in angular-2. Here's how I approached it in ...

Using Node.js to create express routes with nested sub-routes

While experimenting with node.js, I encountered a puzzling issue where a setup works in one instance but fails to work in another instance after making a minor change. In my app.js file: app.use('/musicplayer', require('./routes/music/inde ...

What is the best approach for retrieving specific data from MongoDB in a Node.js application using the GET method?

I have a variety of collections stored on a remote MongoDB server. My objective is to retrieve a specific collection based on the city name. I am currently using POSTMAN to mimic a GET request, but it seems that a different GET method is being triggered: { ...

There was an issue parsing the query: An unexpected character "'"" was encountered in the Graph

Recently, I began delving into the world of GraphQL and have been experimenting with calling our GraphQL server through Postman using JSON format. {"query":"query{stateQuery{avatar(address:'21638103') {action}}}"} However, I ...

Solving Shopify public app session conflicts: Tips and tricks

Recently, I developed a basic embedded public app on Shopify using Node.js for testing purposes. The app functions as expected but I encountered an issue with session clash when opening two stores in the same browser but in different tabs. For instance, ...

"Encountered an error: User.findAll function cannot be found

Here is the content of my user.js file: var sequelize = require('sequelize'); var bcrypt = require('bcrypt'); module.exports = function(sequelize, DataTypes) { const User = sequelize.define('users', { user_id: { ...

Having trouble installing NPM due to node-gyp or microtome?

I have exhausted all possible solutions to fix this error. X Clear npm cache X Start fresh by deleting the repo and starting over X Try switching Node versions between v18.0.0, v16.15.0, v12.22.1 X Reinstall NPM None of these methods have been successful ...

How to stop the execution of a function in Node.js

Currently facing an issue with the route below: router.post('/create', function(req, res, next) { if(!req.user) res.redirect("/"); Survey.find({ surveyName: req.body.surveyName }, function(error, survey) { if(survey) { ...

Only execute the NPM script if there is a staged JavaScript file

How can I ensure that an NPM script runs only when a JS file is staged, specifically after a pre-commit git hook (using Husky)? The scripts in my package.json are as follows: "scripts": { ... "test": "jest", "precommit": "npm test", ... }, ...

Guide to correcting the file path of an external css within the public directory on Express framework

I am facing an issue with loading external CSS files and need some help to fix the path. Despite multiple attempts, I have been unsuccessful so far. Below is my category structure: https://i.stack.imgur.com/sLTcN.png Within the header.ejs file, this is h ...

What could be causing the 500 response code when making a request to the NextJS API route within the app directory?

Every time I attempt to access my API route, a 500 Internal Server Error code is returned The origin of the request export const fetchSuggestion = async () => { const response = await fetch('/api/getSuggestion', { cache: 'no-store&ap ...

Utilizing ngmodel to dynamically populate select dropdowns in Angular version 8

In the form, there are two dropdown menus for selecting start time and end time. The first dropdown menu uses a time array to select a time, and then the index of this selected time is used to create an array for the second dropdown menu. This ensures that ...

How to retrieve the count of documents in a populated collection using Sails.js with MongoDB

I have two models category and inventories and they are associated. The command I used is: Category.find(query).populate('inventories',{select: ['id']}); This command returns the following result: "categories": [ { "inventorie ...