Ka Mok Ka Mok -4 years ago 167
HTTP Question

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

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) => {

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">
<Address2>620 Eighth Avenue</Address2>
<City>New York</City>

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:

I noticed I'm not doing a
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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download