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

Converting a Finsweet hack #4 from jQuery to pure JavaScript in Webflow: Step-by-step guide

I have a jQuery code that I need to convert to pure JavaScript. Can you assist me in translating this code into pure JavaScript? I have left comments in the code to make it easier. ORIGINAL JQUERY CODE: // When the DOM is ready document.addEventListener(& ...

Extracting over 100 tweets from the Twitter API with the help of Node.js

I am facing a challenge while trying to fetch over 100 tweets from Twitter in nodejs as I continuously receive an empty array. Here is the approach I have attempted: const MAX_TWEETS = 200; const TWEETS_PER_REQUEST = 100; async function retrieveTweets(T, ...

Have you ever encountered issues with Promises.all not functioning properly within your vuex store?

I'm currently experiencing an unusual problem. In my Vue project, I have a Vuex store that is divided into different modules. I am trying to utilize Promise.all() to simultaneously execute two independent async Vuex actions in order to benefit from th ...

Safari Glitch in Bootstrap 4

For a simplified version, you can check it out here: https://jsfiddle.net/dkmsuhL3/ <html xmlns="http://www.w3.org/1999/xhtml"> <title>Testing Bootstrap Bug</title> <!-- Bootstrap V4 --> <link rel="stylesheet" href="https://m ...

Exploring the methods for monitoring multiple UDP ports on a single address in Node.js within a single process

I am currently working on developing a Node.js application to manage a small drone. The SDK provides the following instructions: To establish a connection between the Tello and a PC, Mac, or mobile device, use Wi-Fi. Sending Commands & Receiving Responses ...

When the table is clicked, a dynamic accordion table should appear

My current code displays a table inside another table using a PHP for loop. While I can retrieve the data successfully, I'm facing issues with the UI layout and accordion functionality. The inner table is displaying beside the outer table instead of b ...

Using Model.create does not result in the creation of a document immediately; instead, it is resolved as

As I practice creating routes and using a mongodb database, I have encountered an issue: Whenever I attempt to create a new document, it always returns success without displaying the new document or adding it to the database. Here is the response I get in ...

The functionality of the jQuery script is not operating optimally, causing the expected alert to not be displayed

I implemented this jQuery script: $('input[name="add-post"]').on('click', function(form) { form.preventDefault(); for ( instance in CKEDITOR.instances ) CKEDITOR.instances[instance].updateElement(); $.ajax({ typ ...

Using Formik with MUI Multiple Select

Exploring the world of MUI and Formik, I encountered a challenge with creating a multiple Select in my form. It's my first time working with these tools, so I have a question regarding the implementation. Here's what I've tried based on the ...

Transferring an array of interfaces between Angular 2 components

Encountering issues with passing an Array of data between components using @Input. Here is the code snippet: public ngOnInit() { this.applications = new Array<ApplicationEntryInterface>(); (...) let shortTermData = new ShortTermApplicationAdapte ...

How to implement an Angular Animation that is customizable with an @Input() parameter?

Have you ever wondered if it's possible to integrate custom parameters into an Angular animation by passing them through a function, and then proceed to use the resulting animation in a component? To exemplify this concept, consider this demo where t ...

Is your Cloud Functions task generating an Array when querying?

To access items and products in my database, I need to retrieve the "ean" field from the product and check if it matches the one in the request body. The structure of my database is as follows: "cart": { "items": { "0": {info here}, "1": {info ...

Concealed checkbox value in jQuery

I have a problem with setting the hidden checkbox "marketingPhone" to TRUE when the "marketingAAA" checkbox is checked as true. This part works fine. However, if any other checkbox on the page is set to TRUE, then it also sets "marketingPhone" to TRUE. I ...

Retrieving a value using forEach in protractor - Dealing with closures

I am facing an issue with the helper code below, as it is not returning the correct number of occurrences of a string. this.getActualFilteredStatusCount = function(strFilter){ return this.getTotalRows().then(function(count){ var totalCount = ...

Ways to retrieve sorted and updated items in ngx-datatable post-sorting

I am currently utilizing the swimlane/ngx-datatable library to display a list. Within each row of the list, I have implemented an action menu that pops up upon clicking an icon, with dynamically generated items. Challenge: Following sorting, the items app ...

add information to a JavaScript "JSON array"

When working in JS (specifically node/js but applicable to general JS), one common issue arises. Upon receiving JSON data from the server, there is often a need to modify it before presenting it on the view. How should this be approached? Creating additi ...

Utilize JavaScript to extract an image from an external URL by specifying its attributes (id, class)

Is it possible to fetch an image from an external website by using its CSS id or class in conjunction with JavaScript/jQuery's get methods? If so, could someone provide guidance on how to achieve this task? ...

Innovative techniques for class manipulation

Is there a way to implement type checking when extending a class with dynamic methods? For example, if you want to add methods to a class based on options provided to the constructor. This is a common scenario in plain JavaScript. const defaults = { dyn ...

The contents of Ionic views are not stored in a cache, so the controller must

In my ionic application, I have several views. When I launch the app, it takes me to the main view where data is loaded upon initialization of the controller. The issue arises when I navigate away from this view using tabs; sometimes the controller gets d ...

Creating a personalized ESLint rule specifically for Redux reducers

Currently working with Redux and Redux Toolkit alongside ESLint presents a challenge. Sometimes, when adding my extraReducers, I find that I do not need both the state and action properties provided by Redux. As a result, ESLint throws an error in these c ...