Encountering a Issue with Http module in Angular

When attempting to call my API using HttpModule, an error is being thrown upon starting the server (please refer to the screenshot). Error Image

The error arises when I try to make a call to the API from the service using Http.post method.

Here is my app.module.ts:

import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';

import {AppComponent} from './app.component';
import {HeaderComponent} from './header/header.component';
import {AuthComponent} from './auth/auth.component';
import {MarksComponent} from './marks/marks.component';
import {SigninComponent} from './auth/signin/signin.component';
import {SignupComponent} from './auth/signup/signup.component';
import {FormsModule} from '@angular/forms';
import {AppRoutingModule} from './app-routing.module';
import {AuthService} from './auth/auth.service';
import {HttpModule} from '@angular/http';

@NgModule({
declarations: [
AppComponent,
HeaderComponent,
AuthComponent,
MarksComponent,
SigninComponent,
SignupComponent
 ],
imports: [
BrowserModule,
FormsModule,
AppRoutingModule,
HttpModule
],
providers: [AuthService],
 bootstrap: [AppComponent]
})
export class AppModule {
}

This is my service:

import {Router} from '@angular/router';
import {Injectable} from '@angular/core';
import {Http} from '@angular/http';

@Injectable()
export class AuthService {
  constructor(private router: Router, private http: Http) {

  }
  signUpUser(firstName: string, lastName: string, email: string, password: 
  string) {
       const body: [] = [firstName, lastName, email, password];
       return this.http.post('http://localhost:3000/auth/signup', body).map(data 
    => {
            data = data.json();
            return data;
        });
    }
 }

Answer №1

I believe the issue lies not in HTTP, but rather in an incorrect declaration:

Try using this to define the body:

const body = {conge,user};
this.httpClient.post('http://localhost:8080/api/sendconge', body)
.subscribe(data => {
    console.log(data);
});

The httpClient method is recommended for sending data instead of simple http.

Answer №2

Upon reviewing my approach, I realized I had been using the post method incorrectly. Here is the updated version of my code:

registerUser(firstName: string, lastName: string, email: string, password: string) {
// const body: [] = [firstName, lastName, email, password];
const userCredentials = {
    firstName: firstName,
    lastName : lastName,
    email : email,
    password : password
  };
return this.http.post('http://localhost:3000/auth/register', userCredentials);

}

Answer №3

Make sure to assign a data type to the body array.

For example:

const body: any[] = [firstName, lastName, email, password];

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

Adding an item into a list with TypeScript is as simple as inserting it in the correct

I am working with a list and want to insert something between items. I found a way to do it using the reduce method in JavaScript: const arr = [1, 2, 3]; arr.reduce((all, cur) => [ ...(all instanceof Array ? all : [all]), 0, cur ]) During the fir ...

Tips for adjusting HighCharts layout with highcharts-vue integrations

I have a fairly simple component: <template> <div> <chart v-if="!loading" ref="priceGraph" constructor-type="stockChart" :options="chartData" ...

Guide to adding a custom font to your Angular 5 project

I am looking to integrate a new font into my Angular 5 project. So far, I have attempted: 1) Moving the file to assets/fonts/ 2) Including it in the styles section of .angular-cli.json However, it seems that the file is not a regular .css file; it is a ...

Angular - Executing a function in one component from another

Within my Angular-12 application, I have implemented two components: employee-detail and employee-edit. In the employee-detail.component.ts file: profileTemplate: boolean = false; contactTemplate: boolean = false; profileFunction() { this.profileTempla ...

Angular TypeScript test checking file size with Jasmine

Seeking optimal method for testing File size during input type="file" change event. Currently, my test specification appears as follows: it('attach file with too large size', () => { const file: File = { name: 'filename', ...

Exploring the concept of object destructuring in Typescript with imports

Currently, I am in the process of developing the type system for @masala/parser. This allows me to customize the index.d.ts file to fit my needs. When using this as a user, I can: import masala from '@masala/parser' let {C, Stream, F} = masala; ...

How can one effectively access a nested JSON value in Angular by concatenating all fields?

If we have a JSON stored in the variable person like below: { "firstName": "First Name", "lastName": "Last Name", "address": { "city": "New-York", "street": "Some Street" } } To access the value of street, we would typical ...

Angular 4: Unhandled error occurred: TypeError - X does not exist as a constructor

I am currently developing a project in Angular 4, and I encountered an error while running the application. The specific error message is as follows - ERROR Error: Uncaught (in promise): TypeError: index_1.EmployeeBase is not a constructor TypeError: in ...

Error message "Cannot bind to 'name' because it is not a recognized native property" encountered in Ionic icon configuration

Currently, I am developing a mobile app using Ionic 2 and Angular 2. I encountered an issue when trying to use the [name] property in conjunction with Ionic icons and expressions like this: <icon item-right [name]="result.kind ==='song&apo ...

ngFor filter based on user input

I am working on a 2-step stepper feature where I need to filter the values in my amountArray based on the age of the person. If the person is above 50 years old, display only the values 10000 and 15000. For Euro currency, show values 25000 and 50000. I att ...

Transform leaflet marker plugin into Typescript format

I recently discovered a leaflet extension that conceals map markers if they fall outside the boundaries of the current view map. import L from 'leaflet'; L.Marker.MyMarker= L.Marker.extend({}).addInitHook(function (this: ILazyMarker) { this ...

Description: TypeScript type that derives from the third constructor parameter of a generic function

How can I determine the type of constructor props for a generic type? Take a look at this example. type PatchableProps<T> = T extends { [k: string | number]: any } ? { [Key in keyof T]: PatchableProps<T[Key]> } : T | Patch export class ...

Hovering over the Chart.js tooltip does not display the labels as expected

How can I show the numberValue value as a label on hover over the bar chart? Despite trying various methods, nothing seems to appear when hovering over the bars. Below is the code snippet: getBarChart() { this.http.get(API).subscribe({ next: (d ...

Having two buttons in Protractor with identical text displayed

Hello, I'm encountering an issue with my Protractor e2e test: The problem is that I have a menu with a sub-menu. Both the main menu and the sub-menu contain buttons with the same name text (let's call it "menuItem"). I know how to locate and cli ...

Can the individual headers of an ag-grid column be accessed in order to apply an on-mouseover event with a specific method?

In my current project, I am utilizing ag-grid to create a dynamic web-application that combines tools from various Excel files into one cohesive platform. One of the Excel features I am currently working on involves displaying a description when hovering ...

Guide to integrating Keycloak into Angular 6 applications

Looking for assistance on integrating Keycloak into Angular 6. Unsure of where to begin and how to initiate the Javascript Adapter. Can anyone lend a hand? ...

Jest throws an error: require function is not defined

I've been struggling with an issue in Angular for the past 3 days. I'm using [email protected] and [email protected]. I even tried downgrading and testing with LTS versions of node and npm, but I keep encountering the same error. Here ...

The incorrect sequence of Angular/Protractor functions is causing issues within the tests

Trying to extract the values from a column in a grid and compare them before and after sorting can be tricky. I have two functions set up for this task - one to retrieve the initial column values, and another to check the order post-sorting. However, there ...

Error message: "The toJSON method is not found for the item in the nested array of

Encountering an issue with NSwag in my Angular project where it throws an error when attempting to send data if the object contains a nested array of objects like this: export interface IJobAdDto { mainJobAd: JobAddDetailsDto; differentLanguageJobA ...

Effective Management of Uploaded Files

I am currently working on an Angular2 application that interacts with a .NET WebApi to generate text files. Once these files are created, the goal is for users to be able to download them from the application. I am seeking guidance on the best practices ...