having difficulty sending a post request with Angular

Submitting form data via HTTP post will look like this:

     saveDataFile(mutlidata,id,value): Observable<Response> {

        var _url = 'http://xxxx.xxx.xxx';
        var saveDataURL = _url + '/' + id;
        var _this = this;

        let headers = new Headers();
        headers.append('Content-Type', 'multipart/form-data');
        let options = new RequestOptions({ headers: headers });
        const frmData = new FormData();
        frmData.append("file",JSON.stringify(mutlidata),'sample.json');
        frmData.append("dataCheck",value);


        return this.http.post(saveDataURL,frmData, options).pipe(
            map((res: Response) => {
                 return res;
            }),
            catchError(this.handleError),);


    }

The variable multidata will contain:

    [["fakepath/test1.JPG","ea305e-be9d"],["fakepath/test2.JPG","489ce580-c50e-40e6-b1ab-71c7827f636c"]]

    The id will be 15asdas6asd6

    The value will either be true or false

It seems that the form data is not being sent properly. Upon debugging and checking frmdata in return this.http.post(saveDataURL,frmData, options), it displays form.entries, values, etc.

In the sample.json file, I am appending the form data as follows:

frmData.append("file",JSON.stringify(mutlidata),'sample.json');

Here, the term "file" indicates that the data needs to be sent to the API using that keyword.

Answer №1

It is unnecessary to include the Content-Type as the browser will automatically handle it for you. I learned this the hard way when manually adding it to my post request caused the HTTP request to fail. Simply remove that portion of the code.

function saveDataFile(multiData, id, value): Observable<Response> {

  var _url = 'http://xxxx.xxx.xxx';
  var saveDataURL = _url + '/' + id;
  var _this = this;

  const formData = new FormData();
  formData.append("file", JSON.stringify(multiData), 'sample.json');
  formData.append("dataCheck", value);

  return this.http.post(saveDataURL, formData, options).pipe(
    map((res: Response) => {
         return res;
    }),
    catchError(this.handleError),);
}

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

Implementing useState to toggle the checked value of a checkbox in React

When passing a list of checkbox fields with attributes to my component, I want to update the checked attribute based on user selection. However, all I have managed to do so far is double the check value in an array. How can I modify this specific key with ...

Navigating a parameter within an AngularJS directive

I am currently developing a directive that acts as a wrapper for the freebase search widget using jQuery. This is my first attempt at creating a directive and I have encountered some challenges. Here are the functionalities I am aiming for: 1. The ability ...

Having trouble with Javascript files failing to load while hosting a website on digital ocean?

Recently, I developed a web application using an express backend and the ejs view engine. Everything works perfectly fine when tested on my local machine. However, I encountered issues when trying to host it on a digitalocean droplet (Ubuntu 22.10 x64). Af ...

Exploring Custom Validator Comparisons in Angular

Having trouble comparing two input values in a custom validator. An error should occur if the minValue exceeds the maxValue. FormGroup: sumFormGroup = this.formBuilder.group({ from: ['', [Validators.min(0), sumValidator]], to: [&ap ...

Guide on displaying the AJAX response within an HTML or JSP element pulled from a database

description of image 1description of image 2How can I display an AJAX response from a database (map) on a JSP screen? I am able to retrieve the response in the browser console but unsure how to visually render it on the JSP page, like in a table or any ot ...

How to Align Text at the Center of a Line in Three.js

Exploring What I Possess. https://i.sstatic.net/nAtmp.png Setting My Goals: https://i.sstatic.net/svcxa.png Addressing My Queries: In the realm of three.js, how can I transform position x and y into browser coordinates to perfectly align text in th ...

Strategies for organizing your week with a calendar

Hello, I am working on creating a weekly calendar using PHP and I want to add events to the calendar like in this example. However, I am unsure how to display the events in the calendar at the correct time of day. Here is the code snippet I am currently u ...

Generating a chart using solely the existing data components (values)

I have the following arrays: const elements = ['12345', '12346', '12347', '12348', '12349', '12350']; const fruits = ['Apple', 'Ball']; I want to create a Map using array ele ...

Showing an image stored in an array using JavaScript

This script is designed to pull images from a specific location on an HTML page. images = new Array(); images[0] = new Image(); images[0].src = "images/kate.jpg"; images[1] = new Image(); images[1].src = "images/mila.jpg"; document.write(images[0]); I&a ...

Steps to fix the issue of 'Property 'foo' lacks an initializer and is not definitely assigned in the constructor' while utilizing the @Input decorator

What is the proper way to initialize a property with an @Input decorator without compromising strict typing? The code snippet below is triggering a warning: @Input() bar: FormGroup = new FormGroup(); ...

Creating a dynamic HTML table by dynamically populating a column

I have limited experience with javascript, and I am working on a personal project that I enjoy. In the table below, you will find various location names along with their distances from the initial location. This serves as a travel companion for me to refe ...

Using a function as an argument within an Angular directive

Looking for a solution to pass a promise-returning function into a directive? Here's what I'm currently doing: In the parent controller, I've created a callback: $scope.myCb = function(data) { console.log(data); } Directive Scope: sco ...

Having difficulty accessing certain code in TypeScript TS

Struggling with a TypeScript if else code that is causing errors when trying to access it. The specific error message being displayed is: "Cannot read properties of undefined (reading 'setNewsProvider')" Code Snippet if (this.newsShow != ...

What could be causing the issue with my connection.query when using mysql in node.js?

Purpose: The goal is to perform a basic query on the database. Expected Outcome: The console should display "please print something!" along with the results of the query. Actual Outcome: Sadly, nothing appears on the terminal screen. Issues: No error me ...

Retrieve a specific value from an array within Firestore

I am facing an issue where I can only retrieve the values I need from the array by adding a specific string like "اقلام" or "سبورة". However, I want the value to be passed as a prop from another component or screen. Is there a way to resolve this ...

Navigating between components using AngularJS and ExpressJS

Currently, I am embarking on a project that involves utilizing express and angularjs. To guide me through this process, I have been referring to this particular tutorial. Upon my initial attempt of running localhost:3000, I successfully loaded my index.jad ...

What methods do HTML document Rich Text Editors use to incorporate rich text formatting features?

I am curious about the way text in the textarea is styled in rich-text editors. I have attempted to style text in the form but it doesn't seem to change. How does JS recognize the characters typed by the user? Can you explain this process? Edit: Aft ...

Sending data through props to components that can only be accessed through specific routes

File for Router Configuration import DomainAction from './components/domainaction/DomainAction.vue' ... { path: '/domainaction' , component: DomainAction }, ... Linking to Routes using Router Links ... <router-link to="/domainact ...

Angular Error cli command Error: In order to proceed, please provide a command. To see a list of available commands, use '--help'

When I run any command with Angular CLI, I encounter an error. To resolve this issue, I attempted to uninstall and reinstall it by running the following commands: npm uninstall -g @angular/cli npm install -g @angular/cli However, the problem persists an ...

Angular Material Datepicker Input Field Without Icon

Is there a way to eliminate the icon from a datepicker input field? https://i.sstatic.net/BYPZl.png If you need an example, check out: https://material.angular.io/components/datepicker/overview I've only been able to find information on changing the ...