Using Angular 10 to make an HTTP POST request, with the goal of appending a string

Whenever I try to send a post request to an api endpoint, I keep encountering an error with status code 500.

name: "HttpErrorResponse"
ok: false
status: 500
statusText: "Internal Server Error"

Below is the code I am using:

var selectedIds = ["31"];
let sendData = new FormData();
sendData.append('auth', this.dataService.REG_AUTH);
sendData.append('identifier', identifier);
sendData.append('selected[]', selectedIds); 

this.http.post<any>('APIENDPOINT', sendData).subscribe(data => {
  console.log(data);
}, error => {  
  console.log(error);
});

The problem seems to be occurring at this line:

sendData.append('selected[]', selectedIds);
. I'm unsure about how to pass an array to FormData correctly.

I have a functional example from our android app that I need to convert into Angular/Typescript syntax:

@JvmSuppressWildcards
@FormUrlEncoded
@POST("APIENDPOINT")
fun addData(
    @Field("auth") auth: String,
    @Field("identifier") identifier: String,
    @Field("selected[]") selected: ArrayList<String>
): Call<ResponseBody>

After trying some hardcoded fixes without success, I suspect it might be an issue with serialization or data parsing in Angular:

sendData.append('selected%5B%5D', '%2231%22'); 
sendData.append('selected%5B%5D', '31');
sendData.append('selected%5B%5D', 31);
sendData.append('selected%5B%5D', '%5B%2231%22%5D'); 
sendData.append('selected%5B%5D', selectedIds); 
sendData.append('selected%5B%5D', JSON.stringify(selectedIds));

Using selected instead of selected[] does not yield any errors, but no data is updated either. This leads me to believe it's related to serialization or parsing issues.

Answer №1

According to the information provided in this specific answer:

The append() method of FormData is limited to accepting string or blob objects only. If you wish to include an array, you can utilize the JSON.stringify() function to convert your array into a valid JSON string.

formData.append('selectedItems[]', JSON.stringify(selectedIDs));

Answer №2

When you encounter a statusCode 500, it means there is an Internal Server Error, usually indicating a server-side issue. In this case, it's important to verify if the API can properly handle and process your request.

The append() method in FormData accepts either a string or a blob. To pass an array as data, you can use the JSON.stringify() method like this:

formData.append('selectedIds', JSON.stringify(selectedIds));
. Give this a try:

let selectedIds = ["31"];
let sendData = new FormData();
sendData.append('auth', this.dataService.REG_AUTH);
sendData.append('identifier', identifier);
sendData.append('selectedIds', JSON.stringify(selectedIds));

this.http.post<any>('APIENDPOINT', sendData).subscribe(data => {
  console.log(data);
}, error => {
  console.log(error);
});

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

Distinguishing between client side rendering and server side rendering is the backbone of web development

My goal is to give users the option to request webpages from my website either directly from the server or by clicking on links, which will be managed by Backbone's router. When a user requests a webpage directly from the server, they will receive a ...

The functionality of the Bootstrap carousel for moving to the next and previous images is malfunctioning, as it only

The carousel on my website is not functioning properly. It only displays the first image and does not slide to the next pictures as it should. Here is the code snippet for the carousel: <body> </nav> <div id="carousel1" class="carousel slid ...

Is there a method to implement a pop-in animated contact form without the use of Javascript or query selectors?

Although I was successful in creating a contact form with this functionality using Javascript, I encountered some difficulties when attempting to achieve the same result without it. My goal is for the form to slide in from the right when the "open" icon is ...

The HTTP response object in Express does not provide any data in its return

While working on developing a server using express js, I encountered an issue. When I send a get request to my endpoint from another server, the response is received successfully; however, it does not contain the data that was sent by the server after res. ...

The encoding for double quotation marks vanishes when used in the form action

I am attempting to pass a URL in the following format: my_url = '"query"'; when a user clicks on a form. I have experimented with encodeURI and encodeURIComponent functions as well as using alerts to confirm that I receive either "query" or %2 ...

The error message "TypeError: text is not a function" is displayed when trying to utilize the text() method from either Blob

My current dilemma revolves around the usage of functions defined in the typescript lib.dom.d.ts file within my node.js express backend that is implemented using TypeScript. Specifically, I am encountering issues with the File/Blob interfaces where a File ...

Retrieve all direct message channels in Discord using DiscordJS

I need to retrieve all communication channels and messages sent by a bot. The goal is to access all available channels, including direct message (DM) channels. However, the current method seems to only fetch guild channels. client.channels.cache.entries() ...

The functionality of the custom file upload button is experiencing issues on Microsoft Edge

I've been working on creating a unique custom image upload button that functions perfectly in Chrome, Firefox, and Opera based on my testing. However, I'm facing an issue where it doesn't work properly in Microsoft Edge. Feel free to check ...

The setInterval function will run just one time when triggered by an onclick event

After watching a YouTube tutorial on creating desktop notifications, I had an idea to use it as a reminder tool. For example, having a specific reminder appear as a desktop notification every 30 minutes when triggered by clicking a button. However, the cod ...

Error encountered while executing jest tests due to an unexpected import token

Despite trying numerous solutions and suggestions on Stack Overflow, I am still unable to resolve the issue at hand. I recently discovered jest and attempted to use it by following a tutorial on testing React components with jest from DZone. However, when ...

Changing properties of a parent component from a child component in Angular 2

Currently, I am utilizing the @input feature to obtain a property from the parent component. This property is used to activate a CSS class within one of the child components. Although I am successful in receiving the property and activating the class init ...

Encountered an issue while installing the "sharp" module on MAC M1

When I run npm run dev (gatsby develop) on my MacBook Pro M1 chip, it exits with the error message: Error: Something went wrong installing the "sharp" module However, when I run npm run dev on a MacBook Pro with an Intel chip, everything works fine. I&ap ...

Why does the event fail to trigger in an Angular 5 Kendo grid when the last character is deleted from the input box?

I have implemented a multi-filter in my Kendo Grid for an Angular 5 application. However, I am facing an issue where the event is not firing when the last character is deleted from the input box. How can I resolve this issue? For example, if I type ' ...

Instructions for selecting all checkboxes in an HTML table with just one click

Developing an aspx page with 3 HTML tables, I am dynamically adding checkboxes to each cell. Additionally, I have a checkbox outside each table. When I check this checkbox, I want all checkboxes in the corresponding HTML table to be checked. However, curre ...

Showing skeleton placeholders while waiting for the completion of an Array map function in React

I am currently working on a country list component that includes phone codes, country names, and flags. The use of the map() function is causing some delay in loading time. I am looking for a way to determine if the map() function has finished executing or ...

I am retrieving data from a service and passing it to a component using Angular and receiving '[object Object]'

Searching for assistance with the problem below regarding my model class. I've attempted various approaches using the .pipe.map() and importing {map} from rxjs/operators, but still encountering the error message [object Object] export class AppProfile ...

Issue encountered when trying to attach a hover event to the items in a comb

Currently, I am facing a specific situation. The requirement is to display a custom tooltip when the mouse hovers over the combobox items (specifically the "option" tag). Initially, my solution involved using the title tag. While this method worked effecti ...

Selection box and interactive buttons similar to those found in Gmail

Looking to achieve these effects for <option> and <button> using CSS and JavaScript. Any suggestions on how to do this? ...

Having trouble with implementing custom checkboxes in a d3 legend?

My attempt at creating checkboxes in d3 has hit a snag. Upon mouse click, the intention is for them to be filled with an "x". Strangely, using d3.select() inside the click-function doesn't seem to work as expected, although adding the letter U for the ...

show a fresh new page using react router

I have recently developed a mobile app that showcases a collection of movies. Currently, it is static and I am looking to implement a react router for navigation. Specifically, I want the user to be directed to a detail page for a TV Show when they click o ...