angulargrails

415 Unsupported media Type in http.post Angular request


I want to send an http.post (Angular 6) request into my Grails 2.4.2 back-end. I search many solutions in stackoverflow but nothing works. So I'm answering you all.

Current situation:

I'm retrieving my .zip into a dropzone (ngx-dropzone avalaible in npm).I want to send a zip from my angular front-end to my grails back-end. I have a resource Grails which is retrieving my data.

@Path('/api/newmodele')

class NewModeleResource {

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    Response newmodele(){
        CommonsMultipartFile downloadedFile = request.getFile('document')
        return Response.ok("toto" as JSON).build()
   }
}

And I have my Angular post request :

onFilesDropped(myzipConfig: File) {
  let formData = new FormData();
  formData.append('file[]',myzipConfig[0]);
  this.http
      .post(this.backendPOST, formData).subscribe(results=>{
      console.log(results)
  })

}

And I have an error which says : 415 Unsupported Media Type.

Somebody has an idea ?


Solution

  • //pass httpOptions to the function
    
    const httpOptions = {
      headers: new HttpHeaders({'Content-Type': 'application/json'})
    }
    
    this.http
          .post(this.backendPOST, formData, httpOptions).subscribe(results=>{
          console.log(results)
    })