Search code examples
javascriptxmlapipostzendesk

Simple but struggling to convert POST request from using URL params to request body


I was making a POST request in the following manner, using URL params (which worked):

var PAYLOAD = `
  <myxmlcontent>
    <attribute name="id">1</attribute>
    <attribute name="FullName">Joe Bloggs</attribute>
  </myxmlcontent>
`

var URL = 'http://www.somewhere.com/integration?apiKey=company&apiToken=123&payload=' + PAYLOAD;

client.request({
  url: URL,
  type: 'POST',
  contentType: 'application/xml'
}).then(
  function(data) {
    console.log(data);
  }
);

But I wish to put the payload data into the request body.

Is this the correct way to do it? I am not sure, but my attempt has proved unsuccessful so far:

var PAYLOAD = `
  <myxmlcontent>
    <attribute name="id">1</attribute>
    <attribute name="FullName">Joe Bloggs</attribute>
  </myxmlcontent>
`

client.request({
  url: 'http://www.somewhere.com/integration',
  type: 'POST',
  contentType: 'application/xml',
  headers: {
    apiKey: 'company',
    apiToken: '123'
  },
  dataType: 'xml',
  data: 'data=' + JSON.stringify(PAYLOAD)
}).then(
  function(data) {
    console.log(data);
  }
);

I am currently building a client-side Zendesk app.


Solution

  • SOLVED. This is what I had to do (thank you):

    var PAYLOAD = `
      <myxmlcontent>
        <attribute name="id">1</attribute>
        <attribute name="FullName">Joe Bloggs</attribute>
      </myxmlcontent>
    `
    
    var URL = 'http://www.somewhere.com/integration';
    
    client.request({
      url: URL,
      type: 'POST',
      contentType: 'application/x-www-form-urlencoded',
      dataType: 'xml',
      data: {
        apiKey: 'company',
        apiToken: '123',
        payload: PAYLOAD
      }
    }).then(
      function(data) {
        console.log(data);
      }
    );
    

    Helpful article: How are parameters sent in an HTTP POST request?