When using Angular, receiving a "Bad Request" error message with a status code of 400 after making a POST

I am encountering an issue when trying to send register form data to my server as I keep receiving a (Bad Request) error. Interestingly, the server works correctly when tested with postman using the following data:

{
    "username": "root",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="394b56564d795e54585055175a56">[email protected]</a>",
    "password": "Pesho@"
}

However, I am facing problems with Angular and unable to locate where the issue lies.

This is register.component.ts:

export class RegisterComponent implements OnInit {
  public registerFormGroup: FormGroup;

  constructor(
    private readonly auth: AuthService,
  ) { }

  ngOnInit() {
    this.registerFormGroup = this.auth.registerFormGroup(this.registerFormGroup);
  }

  public register(username: string, email: string, password: string) {
    this.auth.register(username, email, password);
    console.log({username});
    console.log({email});
    console.log({password});
  }
}

This is auth.service.ts:

public register(username: string, password: string, email: string): Subscription {
    return this.http.post('http://localhost:3000/auth',
      {
        username,
        email,
        password,
      })
      .subscribe(
        (success: any) => {
          this.notificator.success(success.message);
          setTimeout(() => {
            this.login(email, password);
          }, 1500);
        }
        ,
        (err) => {
          this.notificator.error(err.error.message);
        }
      );
  }

Below is the HTML for the small register form - register.component.html:

<form class="example-form" [formGroup]="this.registerFormGroup"
      (ngSubmit)="this.register(name.value, email.value, password.value)" autocomplete="off">

      <mat-card-content>

        <mat-form-field class="example-full-width">
          <input matInput #name autocomplete="off" formControlName="name" type="text" class="form-control"
          placeholder="Name *">
        </mat-form-field>

        <mat-form-field class="example-full-width">
          <input matInput #email autocomplete="off" #email matInput class="form-control" placeholder="Email *" type="email"
          formControlName="email">
        </mat-form-field>

        <mat-form-field class="example-full-width">
          <input matInput #password formControlName="password" type="password" class="form-control" placeholder="Password *">
        </mat-form-field>

      </mat-card-content>

      <button mat-stroked-button color="accent" class="btn-block" type="submit" value="Sign Up">Register</button>

    </form>

To debug the issue, I included some console logs to verify the data being sent through the form:

{username: "root"} username: "root" proto: Object

{email: "[email protected]"} email: "[email protected]" proto: Object

{password: "Pesho@"} password: "Pesho@" proto: Object

I had successfully implemented a similar logic in a previous Bootstrap project, but seem to face challenges with Material in this case. However, based on the lack of errors in the NestJS server terminal, it does not appear to be related to Material design.

Answer №1

The issue lies in the order of arguments being passed

Here is your register.component.ts:

public register(username: string, email: string, password: string) {
this.auth.register(username, email, password); <---- In this line, you are passing username, email, and password
console.log({username});
console.log({email});
console.log({password});
  }
}

In auth.service.ts: You are expecting username, password, and email in this order

public register(username: string, password: string, email: string): Subscription {
return this.http.post('http://localhost:3000/auth',
  {
    username,
    email,
    password,
  })

To resolve this issue, adjust the order of arguments either in register.component.ts or auth.service.ts

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

Replace interface with a string

Is it possible to override an interface with a string in TypeScript? Consider this example: type RankList = "Manager" | "Staff" interface EmployeeList { id: string, name: string, department: string, rank: "Staff&q ...

Trigger functions on a universal component from the nested component

I am currently working on an Angular project with two components, one being a generic component where the table is defined and the other being a component that invokes this table by passing the required data. However, I encountered an issue where the tabl ...

Navigating through sections in NextJS-14: Utilizing useRef for seamless scrolling

In the past, I had developed an older portfolio website using Vite React + TS and implemented useRef for scrolling to sections from the Navbar. Now, my goal is to transition this portfolio to NextJS 14. I transferred my old components and style folders in ...

Ways to interpret and fix a conflict in npm dependency and understand the output

I'm encountering some issues while attempting to set up my project. The errors I'm running into during the installation process are: npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: @angular-devkit/< ...

Filtering a multi-dimensional array in Ionic 3

I attempted to filter an array from a JSON with the following structure {ID: "2031", title: "title 1", image: "http://wwwsite.com/im.jpg", url: "url...", Goal: "3000000", …} The array is named 'loadedprojects' and below is the filteri ...

Is there a way to easily access the last element of an array in an Angular2 template without the need to iterate through the entire

I'm not trying to figure out how to access looping variables like i, first, last. Instead, my question is about how to retrieve and set variables as template variables. My current approach doesn't seem to be working... <div #lastElement="arr ...

Discovering if the array data is already present in Angular can be accomplished by using specific methods

Here is the snippet of code: data = [ { 'id': 'asdjxv', 'username': 'emma', }, { 'id': 'asqweja', 'username': 'adam', }, { ...

Passing a variable to a cloned template in Angular 2: A guide

When working with Angular2, I encountered an issue with my template code that I am cloning every time a user clicks a button. Despite following instructions provided in this post How to dynamically add a cloned node in angular2 (equivalent to cloneNode), I ...

Using Angular to make a request to a NodeJS+Express server for a simple GET operation

I need help with making a successful GET request from my Angular component to a NodeJS+Express server. someComponent.ts console.log("Before"); // send to server console.log(this.http.get('/email').map((res:Response) => { console.log(" ...

Angular 12 is throwing an error due to the undefined @Input property

The issue presents a simple problem to comprehend yet proves challenging to resolve. There are 2 key components involved: CustomerComponent (Parent) InvoiceComponent (Child) Currently, I'm passing customer details using <admin-invoice-form [custo ...

Tips for establishing optimal parameters for an object's dynamic property

I am working with an array of objects: export const inputsArray: InputAttributes[] = [ { label: 'Name', type: 'text', name: 'name', required: true }, { label: 'User name ...

Determine the tuple data type by analyzing a union of tuples using a single element as reference

Looking for a way to work with a union of tuples: type TupleUnion = ["a", string] | ["b", number] | [Foo, Bar] // ... In need of defining a function that can handle any type K extends TupleUnion[0], with the return type being inferred ...

What TypeScript syntax is similar to Java's "? extends MyClass" when using generics?

How can we indicate the TypeScript equivalent of Java's ? extends MyClass? One possible way to achieve this is: function myFunc <TComponent extends MyBaseClass>(param: ComponentFixture<TComponent>) {} Is there a more concise alternative ...

Issues with typescript compiler when using React-beautiful-dnd

I recently updated react and react-beautiful-dnd to the newest versions and now I am encountering many type errors in my code: {sortedDimensions.map((dimension: any, index: number) => ( <Draggable key={index} ...

Typescript: Maximizing efficiency and accuracy

When it comes to developing Angular2 apps using Typescript, what are the essential best practices that we should adhere to? ...

Oops! Only one request should be open, but it seems there is one too many

I'm encountering an issue while trying to run HTTP unit test cases. My Angular version is 5. Can someone help me with resolving this? Here is the code snippet for a basic GET request: import { TestBed } from '@angular/core/testing'; import ...

Angular Dynamic Alert Service

Is it possible to customize the text in an Angular Alert service dynamically? I'm looking to make certain words bold, add new lines, and center specific parts of the text. Specifically, I want the word "success" to be bold and centered, while the rest ...

Using aliases in npm packages is not supported

I am working on creating an npm package that I want to use in another application. During development, I set a path in tsconfig for importing various modules instead of using a relative path. However, when I download my package into the test app, it is una ...

Guide on importing an ES6 package into an Express Typescript Project that is being utilized by a Vite React package

My goal is to efficiently share zod models and JS functions between the backend (Express & TS) and frontend (Vite React) using a shared library stored on a gcloud npm repository. Although the shared library works flawlessly on the frontend, I continue to e ...

Creating an array of objects in Angular 2

I'm facing an issue with the following expression: public mySentences:Array<string> = [ {id: 1, text: 'Sentence 1'}, {id: 2, text: 'Sentence 2'}, {id: 3, text: 'Sentence 3'}, {id: 4, text: 'Sen ...