Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.8k views
in Technique[技术] by (71.8m points)

typescript - Multipart POST works from Postman but not from Angular Http Client

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...