Error encountered during the http.put() method due to invalid request payload

I'm currently using HttpClient from '@angular/common/http' to perform a PUT operation.

Here is the Angular code snippet I am working with:

public updateDetails(data: Data) {


    const url = '/project/rest/v1/configuration/device/update'
    console.log(JSON.stringify(data));
    let headers = new HttpHeaders();
     headers.append('Content-Type' , 'application/json');


    let body = JSON.stringify(data);

    return this.http.put(url, data, { headers: headers })
      .map(response => true)
      .catch(err => {
        console.log(err);
        return Observable.of(false);
      });

  }

However, I am encountering an issue where I receive the following error:

HttpErrorResponse {headers: HttpHeaders, status: 400, statusText: "Bad Request",

I'm unsure of what I might be missing. I've tried passing the data in stringified format, but it's still resulting in the same error. Any assistance would be greatly appreciated.

Answer №1

It appears that there are two issues to address.

  1. The headers.append function does not alter the existing headers object; instead, it returns a new headers object with the added header.

Therefore, instead of:

let headers = new HttpHeaders();
headers.append('Content-Type' , 'application/json');

You should use:

const headers = new HttpHeaders()
   .append('Content-Type' , 'application/json');

  1. There is no need to stringify the data -

Simply pass the object to the HttpClient, like this:

this.http.put(url, data, { headers: headers })

Answer №2

experiment

let headers = new Headers({ 'Content-Type': 'application/json'});
let configOptions = new RequestOptions({ headers: headers });

sendData(url, jsonData, configOptions) {
    return this.http.put(url, data, options)
}

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 server encountered difficulties locating JSON files within the Assets folder, however it was successful in locating IMG files

After completing my first Angular project and building a portfolio site, I encountered an error when the project tried to locate JSON files. However, it had no problem finding and generating image files in the same assets folder. Interestingly, I could acc ...

What is the best way to clear session/local storage when a user opens a new tab?

What is the best method to clear session/local storage when a user opens a new empty page (tab)? Where should this action be performed? ...

Why does JavaScript not wait for the completion of forEach and instead executes the next line immediately?

While creating my api in nodejs and attempting to push the mongoose return count to a newly created array, it does not wait for the forEach loop to finish before executing json.res() and returning a null response. However, when I use setTimeout(), the re ...

Is there a way to duplicate content (also known as *ngFor) without using a surrounding element?

I am working on an Angular 4 component that utilizes a 2d array structure. I have an array of sections, each containing an array of links. My goal is to display them in a flat format: <ul> <div *ngFor="let section of all_sections"> <l ...

The Power of TypeScript's Union Types

Provided: Reducer only accepts one of the following actions: interface ItemAction { type: 'ADD_TODO'|'DELETE_TODO'|'TOGGLE_TODO', id: number } interface QueryAction { type: 'SET_QUERY', query: string ...

Is there a way to identify changes in screen size in Angular when hiding an element?

During the development of a contact form, I encountered a challenge. After successfully submitting the form, I hide it, but then the footer pops up because the form is hidden: <div class="form-wrapper mat-elevation-z1" [hidden]="successfullySent"> ...

Issues with Array.filter method when used in asynchronous scenarios

I am currently working with Ionic2 / Angular2 utilizing typescript. I have encountered an issue while attempting to filter an Array. The scenario is as follows: let localTours = []; ... let newTours = dbTours.filter(x => localTours.indexOf(x) < 0); ...

Attempting to search for an item by its id within a local json file using Angular

I have a local JSON file containing Kitchen types. I created the KitchenTypesService with two functions inside, GET and FIND(ID). The GET function is working fine, but the FIND function is not working and displaying an error "ERROR TypeError: Unable to lif ...

What is the best way to control the number of pages displayed in pagination?

I have implemented a pagination component in React, but encountered an issue where all pages were being displayed, causing the page to expand and require horizontal scrolling. Is there a way to limit the display to only 20 pages while still allowing for mo ...

Leveraging TypeScript in tandem with React to create stateless components

I'm curious about the distinctions between these variations, in a scenario where state is not being used: 1. export class SkillList extends React.Component<SkillListProps> {} 2. export class SkillList extends React.Component<SkillListProps, ...

The custom marker created with Leaflet using divIcon does not seem to be styled with the specified

I'm currently working on customizing the leaflet marker using a divIcon and custom HTML. My aim is to have my marker displayed similarly to this example: https://i.sstatic.net/a5RnY.png So far, I've managed to create a marker and a divIcon with ...

Tips for adding multiple conditions in an *ngIf statement within Angular 6

Running into navigation issues, <div *ngIf = ("path == '/login'" && "path == '/home'") class="tabs-header-nav"> <a routerLink="/login" class="nav-link active">login</a> <a routerLink="/bb" class="nav-link"& ...

Why does TypeScript permit the storage of incorrect types?

Utilizing Typescript within NodeJS has presented a challenge for me. I defined an interface and assigned it to a variable. However, when I attempt to pass data that does not align with the type specified in the interface - such as passing a number instead ...

It is impossible to add a promise's value to an array

When attempting to push values into an array and return them, the console only displays an empty array or shows undefined! The issue seems to be that .then does not properly pass the value to the array. const net = require('net'); const find = re ...

Creating a sequence of dependent HTTP requests in Angular

Is it possible to execute multiple http get requests sequentially in Angular, where the endpoint URL for the second request depends on the response of the first request? I attempted to nest the requests using the following code snippet: this.http.get(end ...

accessing an array variable within an HTML document

export class FirmsPage { langs; langForm; loading: any; username : string; firms; constructor(public navCtrl: NavController, private navParams: NavParams, public firmService: FirmService, public loadingCtrl: LoadingController) { this.user ...

Incorporating a popover onto a button within an Angular-centric project

Having recently delved into Angular, I decided to create a basic page showcasing details of a legal case. To enhance the visual appeal, I incorporated Angular Material library for its attractive icons, which I intended to display alongside plaintiff and se ...

Accessing Promise.all in the rejection function is not allowed

I have a service that retrieves data, and I make 5 calls to it with different parameters to retrieve various datasets. When the function is successful, everything works fine. However, in case of failure for any of the 5 calls, I need to handle it differen ...

Transform the React useState hooks to accept props and modify the values of these props

I am currently developing a change password feature with validations. Initially, we utilized state hook functions for validating the input (such as one uppercase character, one lowercase, numbers, etc.) and everything was functioning properly. Now, I am t ...

Expanding Rows in a React Data Table: Utilizing Extra Props

Browsing through the documentation for React Data Table, it appears that there is a method to provide additional Props to an expandableRowsComponent. This is an excerpt from the documentation: expandableComponentProps With expandableComponentProps, you c ...