Sending a file using Angular's HttpClient via a POST request with FormData

I am currently working on an Angular 7 project where I am trying to upload an image file along with other form data to a backend using Apache PHP. When I use the HttpClient to send a POST request with just the image alone, everything works smoothly.

// This is successful
uploadAvatar(payload: any): Observable<any> {
    const formData = new FormData();
    formData.set('avatar', payload.avatar);
    return this.http.post(`${api_url}/user/avatar`, formData)
}

// However, this is not
create(payload: any): Observable<any>{
    const formData = new FormData();
    formData.set('title', payload.title);
    formData.set('image', payload.image);
    return this.http.post(`${api_url}/path/to/add`, formData);
}

Unfortunately, the POST request fails due to an OPTIONS preflight issue, where the server indicates that the image file is missing from the request data.

Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

I have attempted manually setting headers to

Content-Type: multipart/form-data
and
Content-Type: application/x-www-form-urlencoded
, but without success.

I also tried using UrlSearchParams and HttpParams instead of FormData, but encountered similar issues.

Interestingly, when testing the request in Postman, it functions correctly.

Answer №1

Postman does not encounter CORS when making requests, as the browser is responsible for implementing the CORS protocol.

Based on the situation described, it seems like there may be an issue with how the PHP application is configured to handle a specific URL. It appears that the application is not properly responding to the OPTIONS request sent by the browser for pre-flight checks (which Postman does not send).

Without seeing the complete error message, it appears that the PHP app is returning a non-200 series response code, such as a 404, to the OPTIONS request.

Answer №2

1) Upon further review, it appears that the issue may indeed be related to a CORS problem with the '/path/to/add' endpoint. It would be wise to investigate any discrepancies in the CORS implementation between the two endpoints on the backend. In order to troubleshoot CORS issues, examining the headers being sent from the client in the browser console's network tab for failed requests/responses is crucial. There is a possibility that your project is automatically adding HttpHeaders (such as through a HttpInterceptor), so determining the actual headers being sent for each request is essential.

2) I am intrigued by your mention of "the server complains that the image file is missing from the request data".. Were there any specific error messages observed in either the client or server-side logs? Providing this information could potentially uncover additional factors contributing to the problem.

3) An alternative suggestion provided elsewhere proposes attempting the upload without 'multi-part/form-data' headers. It may be worthwhile to explore this approach: Upload image with HttpClient

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

An Error occurred: Unable to resolve all parameters for 'ComponentName': ([object Object], ?)

I am encountering an error that I can't seem to figure out. compiler.js:2175 Uncaught Error: Can't resolve all parameters for ClauseListComponent: ([object Object], ?). at syntaxError (compiler.js:2175) at CompileMetadataResolver._getDependencie ...

What steps can be taken to resolve the "value" parameter exceeding the range error in Protractor?

Currently, I am utilizing Angular 7 in combination with Protractor for end-to-end automated test cases. Additionally, I have incorporated BrowserStack for testing my project across multiple browsers. Within my project, there is an image upload feature for ...

Angular conditional operator: running a series of statements

Let's break down the logic: When the enter key is pressed, we want to execute the following conditional statement: if (!elementB.isOpen) { elementB.open(); } else { elementC.open(); elementC.focus(); elementB.close(); } I attempted ...

I'm having trouble getting systemjs to properly connect and download my latest module

Recently, I developed an Angular module that is being downloaded via npm as a private node module in our company registry. Despite setting the default extension to js, my systemjs keeps searching for it in my current directory with any extension. ...

Setting the default sorting order of a Primeng table based on the value of an observable

When using a p-table with sortable columns, I encounter an issue where I want the table to be sorted by a specific column initially. However, the column is not known until run-time so I utilize sortField for that purpose. Here's a portion of the table ...

Discover the steps to extend static generic methods in Typescript

My issue lies in compiling Typescript code as the compiler doesn't seem to recognize the inheritance between my classes. Whenever I attempt to compile, an error arises: Property 'create' does not exist on type 'new () => T'. ...

"Creating a sleek and efficient AI chess game using chess.js with Angular's

Cannot read property 'moves' of undefine Hello there! I am currently working on developing a chess game using Angular. I'm facing an issue with the artificial intelligence in the game where the piece seems to get stuck in the mouse. The l ...

Retrieve all data values from a form using the ngModel directive within an Angular application

I am having trouble retrieving all the values from a form using ngModel. I am only able to get the values from the first text box and not the ones added after clicking the button. For example, you can check this StackBlitz link. Here is the HTML code sni ...

Deciding between a Component, Resolver, or Guard for redirecting authentication in Angular: Which middleware option is the

Incorporating an external authentication system into my Angular application is currently my focus, and I am determined to follow the most effective approach. The authentication process functions in such a way that upon successful authentication from a des ...

"Jest test.each is throwing errors due to improper data types

Currently, I am utilizing Jest#test.each to execute some unit tests. Below is the code snippet: const invalidTestCases = [ [null, TypeError], [undefined, TypeError], [false, TypeError], [true, TypeError], ]; describe('normalizeNames', ...

How can I attach a click event listener to an Angular 2 ui-router <section ui-view> element?

In my Angular 2 application, I have a list called 'views' that contains paths to multiple images. Using ng-repeat, I cycle through these images and display them one by one in a ui-view element. I want to add an event listener so that when an imag ...

Issues with Form Submission in Ionic 3

As a newcomer to Ionic 3 and Angular, I have been working on a login form with form validation in Ionic based on tutorials from Google. Despite following their instructions step by step, I am unable to get my form submitted. I am having trouble pinpointing ...

Instead of tapping the enter key, try searching by keying up

I am implementing a search pipe in Angular for filtering data based on user input import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'searchPipe', pure: false }) export class SearchPipe implements PipeTransform { ...

Angular applications can redirect to their own internal pages when linking to an external URL

I've recently started using Angular and have encountered a minor issue. My routing setup is working as expected in the navbar, but I have a link that points to an external URL. When I click on it, instead of redirecting me to the external site, it ta ...

Angular Material date picker input assumes that the date is in US format

While entering the date manually in the input field (without using the datepicker), the date format defaults to US format. For instance, if you type in "10/01/2019" in the input field, it changes to "01/10/2019" and when you open the date picker, it displa ...

Using Typescript: Attempted to change the property type from a library and received the error "Subsequent property declarations must have the same

Is there a way to override the property type from a library declaration? I attempted to do so using an interface but received an error stating Subsequent property declarations must have the same type. How can this issue be resolved? // Library Declaration ...

Incorporate a 'Select All' functionality into ion-select by adding a dedicated button

Looking for a way to set custom buttons on ion-select through interfaceOptions in ionic 4? HTML <ion-item> <ion-label>Lines</ion-label> <ion-select multiple="true" [(ngModel)]="SelectedLines" [interfaceOptions]="customAlertOption ...

Updating an Object using Angular's @Input() feature

I am facing an issue with my GameStats Object, which is part of a self-defined interface. When I update the value of an attribute, the child component does not recognize the change. I have tried using ngOnChanges, but it does not get triggered, and ngDoChe ...

The "main" entry for ts-node is not valid when running ts-node-dev

Recently, I embarked on a TypeScript project using yarn where I executed the following commands: yarn init -y yarn add typescript -D yarn tsc --init yarn add ts-node-dev -D Subsequently, I crafted a script titled dev that triggers tsnd src/index.ts, howev ...

TypeScript causing issues when multiple selectors are used

Currently, I have a function that allows me to search for HTML elements based on text content: function findElementsByText(text: string): HTMLElement[] { const selectors = 'button' // This conditional statement ensures that an empty text quer ...