Angular 5 'Content-Type': 'multipart/form-data' gets reset to 'application/json'

Issue

Hi I am having trouble trying to get my httpClient patch request to send FormData with content type ‘multipart/form-data’.

I have specified the headers as shown:

  private httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'multipart/form-data', 'Cache-Control': 'no-cache', 'Pragma': 'no-cache'
    })
  };

And I do the following to save to the nodejs server:

const formData: FormData = new FormData();
formData.append('materialFile', 'something');
return this.httpClient.patch<any>(this.apiUrl  + loan.id, formData, this.httpOptions);

On my Nodejs/Express server I do the following:

const Multer  = require('multer');

router.patch('/:id', Multer().fields([{ name: "materialFile", maxCount: 1 }]), (req, res, next) => {
  console.log(req.files['materialFile']);
});

When I inspect the request headers on the browser I see that the content-type is application/json.

Anybody knows why?

Solution

Angular tries to automatically set http header content-type according to request body, so there is absolutely no need to set it manually. If the content-type header is application/json in browser’s devtools that means request body has been changed till angular’s attempt to define the header. That change most probably happens in interceptors. So if you have an interceptor, that makes manipulation on the request, the issue is probably at that point.

Answered By – Hikmat G.

Answer Checked By – Willingham (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.