You have to include the necessary request body in the front-end request to address the

After successfully testing a POST request to add a new entity to the database from my project back-end using Postman, I encountered an error when trying to do the same from the front UI (I'm using Angular 4): Required request body is missing.

Failed to load resource: the server responded with a status of 500 (Internal Servlet Error)

I suspect there might be an issue with my TypeScript code. Can anyone assist me with this?

<form (ngSubmit)="createEntity()">
    <div class="form-group">
      <label for="code">Code</label>
      <input type="text" [(ngModel)]="code" placeholder="Code" name="code" class="form-control" id="code">
    </div>
    <div class="form-group">
      <label for="description">Description</label>
      <input [(ngModel)]="description" placeholder="Description" name="description" class="form-control" id="description">
    </div>
    <div  class="form-group">
       <label for="type">Type</label>
      <p-dropdown [(ngModel)]="type" [options]="entityTypes" filter="filter" name="type" placeholder="Type" [style]="{'width':'100%'}">
      </p-dropdown>
    </div>  
        <div  class="form-group">
       <label for="profil">Profil</label>
       <p-dropdown [(ngModel)]="profil" [options]="entityProfiles" filter="filter" name="profil" placeholder="Profil" [style]="{'width':'100%'}">
      </p-dropdown> 
    </div>
    <div class="form-group">
      <label for="number">Number</label>
      <input [(ngModel)]="number" placeholder="Number" name="number" class="form-control" id="number">
    </div>
    <button type="submit" class="btn btn-success">Submit</button>
  </form>


Thank you in advance :)

Answer №1

If you need help with service and component functions, take a look at this code snippet.

Appservice.ts file

        import { Injectable } from '@angular/core';
        import { Http, Response, ResponseContentType } from '@angular/http';
        import { Observable } from 'rxjs/Observable';
        import { Jsonp, URLSearchParams } from '@angular/http';
        import { Headers, RequestOptions } from '@angular/http';
        import 'rxjs/add/observable/throw';
        import 'rxjs/add/operator/catch';
        import 'rxjs/add/operator/map';
        import { HttpHeaders } from '@angular/common/http';
        @Injectable()
        export class AppService {
            utcOffset = -(new Date().getTimezoneOffset());
            private CONTENT_TYPE_JSON = 'application/json';
            private CONTENT_TYPE_FORM_DATA = 'application/x-www-form-urlencoded';
            private ACCEPT = 'application/json';
            private UTC_OFFSET;
            private PLATFORM = 'WEB';
            private APP_VERSION = '1.00';
            private VERSION = '1.0';

            constructor(private http: Http) {
                const offset = this.utcOffset / 60;
                this.UTC_OFFSET = offset.toString();
            }

            postJSONData(apiUrl: string, value: Object): Observable<any> {
                const body = value;
                const headers = new Headers();
                headers.append('Content-Type', this.CONTENT_TYPE_JSON);
                headers.append('utc-offset', this.UTC_OFFSET);
                headers.append('platform', this.PLATFORM);
                headers.append('app-version', this.APP_VERSION);
                headers.append('version', this.VERSION);
                headers.append('accept', this.ACCEPT);
                if (localStorage.getItem('userData')) {
                const user = JSON.parse(localStorage.getItem('userData'));
                headers.append('token', user.token);
                headers.append('session', user.session);
                }
                return this.http.post(apiUrl, body, { headers: headers })
                .map(this.extractData)
                .catch(this.handleServerError);
            }

            private extractData(res: Response) {
                    let body = res.json();
                    var headers = res.headers;
                    if (body.status == 500) {
                    let error = body;
                    let errMsg = (error.msg) ? error.msg : ((error.status) ? `${error.status} - ${error.statusText}` : 'Request error');
                    }
                    return body || {};
            }
            private handleServerError(error: any) {
                    const defaultErrorMsg = 'Internal server error, please try again';
                    const customError = 'Could not connect to the server. Please try again later';
                    // `${error.status} - ${error.statusText}`
                    const errMsg = (error.message) ? error.message : ((error.status) ? customError  : defaultErrorMsg);
                    return Observable.throw(errMsg);
            }
        }

Function

   this.appService.postJSONData(URL, data).subscribe(result => {
            console.log(result);
            }, err => {
                console.log(err);
            });

Answer №2

Issue Resolved :)

Fix : I switched to using HttpClient instead of the outdated http method And here is the updated code snippet :

   //service
   CreateEntity(entity) {
        const entityUrl = this._entity;
        return this.httpc.post(entityUrl, entity);
    }
    
    
   //ts
   
   entity = new Entity();
   
    createEntity(): void {
    
        this.EntitySRV.CreateEntity(this.entity)
            .subscribe(data => {
                 this.submitted = true;
            });
    }  
    
    
   
    
  <form>
    <div class="form-group">
      <label for="code">Code</label>
      <input type="text" [(ngModel)]="entity.code" placeholder="Code" name="code" class="form-control" id="code">
    </div>
    <div class="form-group">
      <label for="description">Description</label>
      <input [(ngModel)]="entity.description" placeholder="Description" name="description" class="form-control" id="description">
    </div>
    <div  class="form-group">
       <label for="type">Type</label>
      <p-dropdown [(ngModel)]="entity.type" [options]="entityTypes" filter="filter" name="type" placeholder="Type" [style]="{'width':'100%'}">
      </p-dropdown>
    </div>  
        <div  class="form-group">
       <label for="profil">Profile</label>
       <p-dropdown [(ngModel)]="entity.profile" [options]="entityProfiles" filter="filter" name="profile" placeholder="Profile" [style]="{'width':'100%'}">
      </p-dropdown> 
    </div>
    <div class="form-group">
      <label for="number">Number</label>
      <input [(ngModel)]="entity.number" placeholder="number" name="number" class="form-control" id="number">
    </div>
    <button (click)="createEntity()" class="btn btn-success">Submit</button>
  </form>

Success! :D

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

"Learn the process of integrating Javascript files from the Angular assets folder into a specific Angular component or module (such as Angular 2, 4,

I have custom1.js, custom2.js, and custom3.js JavaScript files that I need to load into Angular components component1, component2, and component3 respectively. Instead of adding these files to the index.html globally, I want to load them specifically for e ...

Guide on enabling the Access-Control-Allow-Origin feature for Angular 5 and Node.js:

After exploring various methods to include 'Access-Control-Allow-Origin', I have not been successful in resolving the issue. I am utilizing the @angular/common/http module with an external URL as a data source. However, when attempting to retrie ...

Switch the icon in Angular 2 while using ngFor loop

One issue I am facing with my angular2 project is that the icon does not appear when the page loads, but only after clicking. The array being used is called "keys". <ion-grid class="dueD-line" *ngFor="let line of keys; let i=index"> <div style= ...

Mocking a named class-export in TypeScript using Jest

I have a node module that exports several classes, including one called Client, which I utilize to create clients with various APIs as methods. I'm currently attempting to test my module, which has a dependency on this node module, using Jest. Howeve ...

Sign out from Azure Active Directory using the ADAL library in an Angular application written in TypeScript

When navigating multiple tabs in a browser, I am encountering an issue with logging out using adal. How can I successfully log out from one tab while still being able to use another tab without any hindrance? Currently, when I log out from one tab, it pr ...

The generic parameter is extending a type but is being used in a contravariant position, causing TypeScript to struggle to unify it

When developing my functions, I aim to provide flexibility for consumers to use a wider type. However, I encounter issues when the type is used in a contravariant position and TypeScript raises complaints. Here is the simplified code snippet: function wra ...

Issue arose when attempting to remove an item from an array within React

I have a handleAd function that adds new components to an array, and I also have a handleDelete function that is supposed to remove the selected element from the array. I am generating unique keys for each element to prevent deletion issues. Initially, th ...

TypeScript's type 'T' has the potential to be instantiated with any type, even if it is not directly related to 'number'

Let's say we have a function that takes a value (for example, number) and a callback function that maps that value to another value. The function simply applies the provided callback: function mapNumber<T>(value: number, mapfn: (value: number) = ...

Tips for resetting and enabling file uploads with ng2-file-upload

My file upload functionality is working smoothly using ng2-file-upload. However, I am facing a challenge in handling server-side errors and resetting the file uploader. How can I achieve this? Below are the snippets of code that I am currently using: HTML ...

By utilizing a function provided within the context, React state will consistently have its original value

After passing functions from one component to its parent and then through context, updating the state works fine. However, there is an issue with accessing the data inside these functions. They continue to show as the initial data rather than the updated v ...

Error encountered while retrieving data from Firebase and storing it in an array within an IONIC application

I am currently working on a function that retrieves data from Firebase's real-time database and stores it in an array for mapping in React. However, I am encountering a TypeScript error that I'm having trouble resolving. The error message reads ...

Passing a complex variable type in TypeScript to a function without the need to redefine the type

I'm fairly new to working with TypeScript and I've encountered this issue several times. When using tools like Prisma to retrieve data, I often come across values with incredibly complex types. These values contain many attributes, which is perf ...

Should I use connect or refCount with Angular and rxjs?

I was pondering how to reuse data from observables, so I decided to hold an observable and manipulate the data using map operators after researching and seeking advice. By making a single HTTP request, storing it in a variable, and manipulating it there, I ...

Having trouble choosing multiple options from autocomplete drop-down with Selenium web-driver in Python

I am currently in the process of automating a webpage built with Angular that features an auto-complete dropdown with numerous elements. My goal is to click on each individual element and verify if it populates all the fields below accordingly. Below is th ...

Checking the text both before and after clicking a link by using a method such as content verification

Currently, I am encountering an issue with validating the text on my links before and after they are clicked. If the link text reads "one two" before clicking and remains as "one two" after the click, then the test case passes. However, if the text change ...

What is the method for dynamically assigning a name to ngModel?

I have the following code snippet: vmarray[]={'Code','Name','Place','City'} export class VMDetail { lstrData1:string; lstrData2:string; lstrData3:string; lstrData4:string; lstrData5:string; ...

"Transform the appearance of the datepicker input field with Material 15's dynamic

I am in need of assistance to change the color to white for the input date and add an underline to a datepicker element <mat-form-field class="date-criteria-select " [floatLabel]="'always'"> <mat-label class=" ...

The distinction between <Type>function and function name():Type in TypeScript is essential to understand the various ways

function retrieveCounter(): Counter { let counter = <Counter>function (start: number) { }; counter.interval = 123; return counter; } Upon inspection of line 2 in the code snippet above, I am left wondering why I am unable to use function ...

A more concise validation function for mandatory fields

When working on an HTML application with TypeScript, I encountered a situation where I needed to build an error message for a form that had several required fields. In my TypeScript file, I created a function called hasErrors() which checks each field and ...

Choosing the desired option in Angular 4+ with Chrome selected

I have been facing an issue where I am unable to set a selected value of an option that is fetched from a database and passed into an @Input. Even though the value is successfully passed into the control, the option remains unset and defaults to the first ...