2

I currently have this section in a function of an Ionic application that uses Angular and Capacitor. The function is for uploading a file using a FormData post.

        var data = new FormData();
        data.append(name, blobFile, "TestName");
        data.append('fileId', params.fileId);
        data.append('pagenumber', params.pageNum); 
        data.append('appid', this.appMod.appId);
        data.append('sessionid', this.appMod.sessionId);
        ...
        return this.http.post(
             webServiceUrl,
             data,
             {headers: new HttpHeaders({'Content-Type': undefined})},
             );

With this.http being the Angular HttpClient. When this section runs, it reaches the http.post however what is returned is the following error

SyntaxError: Unexpected token o in JSON at position 1

Checking network activity, this post never actually sends out any network requests leading me to believe this is not an issue with the backend

From what we have tested we tried setting 'Content-Type': 'application/x-www-form-urlencoded' and adding responseType: 'text' in the HttpOptions however both did not fix the issue. In addition I have repeatedly made sure that the webServiceUrl is correct.

I have no idea what could be causing this issue so any insight will be helpful

Alex Druzenko
  • 67
  • 1
  • 9

1 Answers1

0

It seems there were some earlier versions that had issues with detecting or setting multipart/form-data - the Content-Type you should be using as per this SO answer.

I have verified, when using your exact code in Angular 14, the Content-Type is correctly set and the request is sent if no Content-Type is specified when passing a FormData object to the HttpClient's post method.

    return this.http.post(webServiceUrl, data, {
      // headers: new HttpHeaders({ 'Content-Type': '' }),
    });

You might still have to set responseType: 'text' as you indicated earlier.

So your resolution will be a combination of

  1. Checking your (possibly old) Angular version for problems in this area (see link above)
  2. Not setting a Content-Type as it's inferred from the passed object
  3. Making sure you have set your responseType to match the server's return type
  4. Checking if you have any HttpInterceptors that might be overriding Content-Type or causing conflicts otherwise
Theunis
  • 436
  • 3
  • 14