Angular 6 - httpClient posting an XML file

11,468

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));
  }
Share:
11,468

Related videos on Youtube

Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    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?

    • user184994
      user184994 almost 6 years
      Just change postedData to your XML string
    • justMe
      justMe almost 6 years
      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.
  • Francesco Gabbrielli
    Francesco Gabbrielli about 3 years
    it's response-type: 'text' as 'json' and should go outside 1 level, after headers: {...}. See stackoverflow.com/questions/50826531/…