1

I'm trying to upload a google maps-like review that has some content and optional images attached to it.

I've tried it first in Postman and it seems to work great, however I'm having a lot of trouble sending the same request in Angular.

This is the postman request (it has default Headers with Content-Type: multipart/form-data): enter image description here

And this is the angular service that tries to make the same request with form-data:

  addMultipart(review: Review, files: FileList): Observable<Review> {
    const formData = new FormData();
    for (let i = 0; i < files?.length || 0; i++)
      formData.append('files', files[i]);

    formData.append('review', JSON.stringify(review));

    let opts = {
      headers: new HttpHeaders({
        // 'Content-Type': 'multipart/form-data
        'Content-Type': 'application/json',
        'Accept': '*/*',
      }),
    };

    return this.http
      .post<Review>(this.url, formData, opts)
      .pipe(catchError(this.handleError<Review>()));
  }

Now, if the request content-type is application/json like in the code above, I get an error that says Required String parameter 'review' is not present, even though the payload contains form-data with name review enter image description here

And if I set content-type to multipart/form-data like in Postman, I get the CORS error: enter image description here

I'm honestly pretty clueless about what's causing this error so any help is greatly appreciated! :D

3
  • you need to set cors policy in your server Commented Jan 23, 2021 at 4:40
  • It turns out that removing the Content-Type header altogether seems to work. Commented Jan 23, 2021 at 4:51
  • Thanks @95xxxtent. The tip has really helped. As far as I see this, the multipart form data content type header with boundary is added by the angular http client automatically. So if we set the content type explicitly, it breaks the boundary addition. So just removing the Content-Type header for the upload endpoint fixed the problem. Commented Jun 27, 2023 at 3:21

1 Answer 1

2

to fix CORS error in develop environment : you can install the Allow-Control-Allow-Origin plugin The quickest fix you can make is to install the moesif CORS extension . Once installed, click it install the Allow-Control-Allow-Origin plugin The quickest fix you can make is to install the moesif CORS extension . Once installed, click it in your browser to activate the extension. Make sure the icon’s label goes from “off”: your browser to activate the extension. Make sure the icon’s label goes from “off”:

to fix that in production environment : this is good article

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.