Sending a POST request to an API with Angular and passing an object as the payload

I'm currently working on adding a feature to my app where I can take the products from an order and send them to the cart, essentially replicating the entire order.

While I have successfully retrieved the order, I am facing difficulty in sending it back to the API using the POST method.

The API call in the cart.service.ts file is as follows:

  repeatOrder(products: SingleOrder['products']) {
    return from(Preferences.get({key: 'TOKEN_KEY'})).pipe(
      switchMap(token => {
        const headers = new HttpHeaders().set('Authorization', `Bearer ${token.value}`);
        const formData: any = new FormData();
        formData.append('products', products);
        return this.httpClient.post(`${environment.apiUrl}cart/repeatorder`, formData, {headers, observe: 'response'});
      }),
      catchError(err => {
        console.log(err.status);
        if (err.status === 400) {
          console.log('Error 400: ', err.error.message);
        }
        if (err.status === 401) {
          this.authService.logout();
          this.router.navigateByUrl('/login', {replaceUrl: true});
        }
        return EMPTY;
      }),
    );
  };

Additionally, here is the repeat purchase function in the order-view.page.ts file:

  repeatThisPurchase() {
    this.repeatOrderArr= [...this.orderProducts];

    this.cartService.repeatOrder(this.repeatOrderArr).subscribe(
      data => {
        console.log('Data sent to cart: ', data);
      },
      error => {
        console.log('Error', error);
      }
    );
  }

Lastly, here is the button I utilize to invoke the repeatPurchase function:

<div class="btn-wrapper">
  <ion-button color="vigros" class="purchase-btn" size="default" type="submit" (click)="repeatThisPurchase()" expand="block">Ponovi nakup</ion-button>
</div>

Upon inspection of the console in my browser, I am encountering a 500 error, and the payload in the Networks tab displays: products: [object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

Could you point out where I might be going wrong?

Answer №1

Avoid using formdata unless necessary (formdata is typically used for sending files).

const headers = new HttpHeaders().set('Authorization', `Bearer ${token.value}`);

return this.httpClient.post(`${environment.apiUrl}cart/repeatorder`,{ products }, { headers });

Are you aware of the expected request body format for your API?

Answer №2

Take a look at the documentation for append:

value

The value of the field can be either a string or a Blob (including subclasses like File). If no specific value type is provided, it will be converted to a string.

In this case, you are using:

const formData: any = new FormData();
formData.append('products', products);

From the result, it seems that products is an array of objects (as indicated by a comma-separated list of [object Object] when converted to a string).

You will need to somehow encode the data. The method may vary depending on how your server-side code processes it, but one potential solution is to encode each object as JSON and append them individually, labeling them as an array using [] at the end of the name for PHP and certain Node.js libraries:

products.forEach(product => {
    formData.append('products[]', JSON.stringify(product));
}); 

It is important to note that the approach may differ based on your server-side code. It might be more effective to encode products as JSON and send an application/json formatted request instead of using FormData for a multipart/form-data request.

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

Exploring the creation of an Angular service that utilizes HttpClient for making GET requests, with a focus on the different

I've been diving into Angular lately and I'm facing some challenges with handling get requests. If you're interested, you can check out my code on Angular Stackblitz import { HttpClient} from '@angular/common/http'; import { Inject ...

Cannot perform table inserts or creates with NestJS Sequelize functionality

I am currently in the process of setting up a small web server with a MySQL database. To achieve this, I am utilizing NestJs along with Sequelize. However, as I am still in the learning phase, I seem to be encountering an error: Within my database, I have ...

Tips for correctly specifying the theme as a prop in the styled() function of Material UI using TypeScript

Currently, I am utilizing Material UI along with its styled function to customize components like so: const MyThemeComponent = styled("div")(({ theme }) => ` color: ${theme.palette.primary.contrastText}; background-color: ${theme.palette.primary.mai ...

Merge a pair of observables to create a single combined output

Hey there, I'm currently diving into the world of RxJS and reactive programming. One challenge I'm facing is merging two observables. The first observable contains an array of objects called DefectImages[], while the second observable holds an ar ...

Rendering with node.js express inside nested JS files

Imagine I have a basic view <html> <head> <title>something</title> </head> <body> <%= param %> </body> <script type="text/javascript" src="myscript.js"></script> </html> Be ...

Issue with JavaScript: Flag set to false does not halt the simple animation

My goal is to initiate animations when the mouse is pressed down and then immediately halt them once the mouse is released. Upon pressing the mouse, I set a flag to true which triggers the animation of the corresponding button that was clicked. However, t ...

Facing a problem with Angular JS where the get method is resulting in a 405 error

Hey there, I have a service that is written with the following method: var GetData = function (token) { $http.defaults.headers.common['Authorization'] = 'Bearer ' + token; var response = $http.get(baseurl + "api/controller/sea ...

How to get the total number of rows/records in a JSON store using ExtJS?

My dilemma involves a JSON store that provides data in JSON format. I am currently attempting to determine the number of rows or records in the JSON string. However, when utilizing the store.getCount() function, it consistently returns 0. Strangely, the ...

Handling Datatable: Executing an asynchronous function post an Ajax request

Upon receiving data from the web server, I want to manipulate it in Datatable. However, the response data is encoded and requires decoding using an asynchronous function called decodeData(). I attempted to call this async function in the dataSrc section as ...

Storing the compiled TypeScript file in the source file's directory with the TypeScript compiler

I am in need of assistance with compiling TypeScript files (ts) into JavaScript files (js) and mapping files (js.map) all within the same directory as the source file. I have attempted to configure this in my tsconfig.json file using: { "compilerOption ...

The function res.render is not displaying the new page

I have a task that seems straightforward. On my header, I am loading a few a links. <a class="nav-link" href="menu">Menu 1</a> I am attempting to access the URL /menu from this link. In my app.js file: app.use('/', index); app.us ...

How come I can never seem to make it past the number 1?

My ultimate goal is to develop a program that can decipher a word search puzzle from a 2D array using pointers exclusively. In the main function responsible for executing the actual word search, I have integrated a while loop designed to continue as long a ...

Can you switch out the double quotation marks for single quotation marks?

I've been struggling to replace every double quote in a string with a single quote. Here's what I have tried: const str = '1998: merger by absorption of Scac-Delmas-Vieljeux by Bolloré Technologies to become \"Bolloré.'; console ...

Breaking apart a pipe-separated text and sending it through a JavaScript function

CSS: <div class="pageEdit" value="Update|1234567|CLOTHES=5678~-9876543?|5678"> <a href="https://host:controller">Update</a> </div> Trying to retrieve the data within the div and pass it into a JavaScr ...

What are some strategies for improving the efficiency of this function that includes three loops?

In my project, I have developed a function that iterates through various elements in a gantt chart that denote tasks. Each task is identified by the class "link" and attributes "id" and "pre". The attribute "pre" signifies the predecessor task for each sp ...

Show a notification if the search bar returns no results

I am facing an issue with my search functionality. When a user searches for something not in the list, an error message should be displayed. However, in my case, if I search for "panadol" in my list, it displays the list containing that word and shows an e ...

What process is involved in implementing TCO (Tail Call Optimization) for a recursive anonymous function in ES5?

Is there a way to optimize an anonymous recursive function for tail call optimization, similar to how a named recursive function can be optimized? If such a method exists, please provide explanations on how to achieve it. Below is an example of a recursi ...

Is NPM enterprise necessary for Angular2 and Java development?

Is an NPM enterprise version necessary if I plan to utilize Angular2 with Java as the backend technology for developing applications within my organization, without using Node JS or NPM server? ...

Is there a way for me to retrieve the information within this function? It seems like it may be a promise, but I am uncertain

I need help extracting the data from doc.data and sending it to another component based on the dropdown selection. It appears that the data is in promise format, and despite trying async/await, I am struggling to access it. Can anyone guide me on how to ...

How can we ensure that React state remains unaltered when modifying an array set to state?

Hope you're having a wonderful day! I'm encountering a significant problem with React. I have a state that contains an array. Within a function, I create a copy of the state in a new variable. However, any modifications made to this new variable ...