Ka Mok
Ka Mok

Reputation: 1988

How to POST an XML with Angular http?

I'm having trouble using JavaScript to send xml. I've tried to emulate what many others have done, but I'm not getting success. I'm getting a XML Syntax Error: Please check the XML request to see if it can be parsed. with the code 80040B19.

Here's my code. I'm trying to use the USPS Address Validation API. On page 4 of this doc, there's more info.

const apiUrl = 'http://production.shippingapis.com/ShippingAPI.dll?API=Verify';

validate(address: Object): any {
    const payload = this.xmlBuilder.buildObject({
      AddressValidateRequest: {
        $: { USERID: 'XXXXXXXXX' }, // api key hidden
        Address: {
          $: { ID: '0'},
          FirmName: null,
          Address1: address['address2'], 
          Address2: address['address1'], // NOT A TYPO, they swap it
          City: address['city'],
          State: 'NY',
          Zip5: address['postal_code'],
          Zip4: null
        }
      }
    });
    console.log(payload); // SEE BELOW
    const headers = new Headers({ 'Content-Type': 'text/xml' });
    const options = new RequestOptions({ headers: headers });
    return this.http.post(this.apiUrl, { 'XML': payload }, options)
      .map((res) => {
        this.parseXMLStringToObject(res.text(), (err, result) => {
          console.log(result);
        });
      });
  }

Here's what my console.log on the payload reads. I've verified this to the letter, from the order of the xml tags, to what is required tag but optional value. I'm positive the payload is correct.

<AddressValidateRequest USERID="XXXXXXXXX">
  <Address ID="0">
    <FirmName/>
    <Address1/>
    <Address2>620 Eighth Avenue</Address2>
    <City>New York</City>
    <State>NY</State>
    <Zip5>10018</Zip5>
    <Zip4/>
  </Address>
</AddressValidateRequest>

One thing that I can think of is I'm somehow not using the http correctly, and I'm sending a blank xml somehow.

On their docs, they have this listed: https://servername/ShippingAPI.dll?API=Verify&XML=……..

I noticed I'm not doing a XML in the url, but I'm assuming that when I input the Content-Type: text/xml, that it get converted. I've also tried application/xml which give the same error.

Upvotes: 0

Views: 1048

Answers (1)

Alex Mufatti
Alex Mufatti

Reputation: 41

From the documentation on USPS website it seems that the call isn't a POST with the XML as payload but a GET with XML (I suppose urlencoded) in the URL XML parameter.

Upvotes: 1

Related Questions