2

I am using Angular 6 httpClient and have this code in a service:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'text/xml' })
};

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  constructor(private http: HttpClient) { }

  post() {
      const postedData = { userid: 1, title: 'title here', body: 'body text' };
      return this.http.post('this url here', postedData, httpOptions).subscribe(result => {
        console.log(result);
      }, error => console.log('There was an error: '));
  }

}

My question is: I want to post an xml file so how do I modify this code to do that?

  • 1
    Just change `postedData` to your XML string – user184994 May 07 '18 at 12:43
  • Add 'content-type' header and optionally 'accept' `const headers = new HttpHeaders(); headers = headers.append('Content-Type': 'text/xml'); headers = headers.append('Accept', 'text/xml');` Then send your payload as string. – justMe May 07 '18 at 13:30

1 Answers1

4

You want to POST XML data? You need a 'Content-Type' Http header.

If you want to also receive XML, your options for a response type are json, text, blob, and arraybuffer. XML is not an option, so you ask for it as plain text but (depending on your API server) you want to set the Accepts type 'application/xml' and your Response-Type to 'text'.

post() {
  // Set your HttpHeaders to ask for XML.
  const httpOptions = {
    headers: new HttpHeaders({
      'Content-Type':  'application/xml', //<- To SEND XML
      'Accept':  'application/xml',       //<- To ask for XML
      'Response-Type': 'text'             //<- b/c Angular understands text
    })
  };
  const postedData = `
    <userid>1</userid>
    <title>title here</title>
    <body>body text</body>`;

  return this.http.post('this url here', postedData, httpOptions)
    .subscribe(
      result => { 
        console.log(result);  //<- XML response is in here *as plain text*
      }, 
      error => console.log('There was an error: ', error));
  }
Rap
  • 6,851
  • 3
  • 50
  • 88
  • it's response-type: 'text' as 'json' and should go outside 1 level, after headers: {...}. See https://stackoverflow.com/questions/50826531/httpclient-post-tries-to-parse-a-non-json-response – Francesco Gabbrielli Mar 18 '21 at 00:28