简单但难以将 POST 请求从使用 URL 参数转换为请求正文

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

我使用 URL 参数(有效)以下列方式发出 POST 请求:

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);
  }
);

但我希望将负载数据放入请求正文中。

这是正确的做法吗?我不确定,但到目前为止我的尝试被证明是不成功的:

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);
  }
);

我目前正在构建客户端 Zendesk 应用程序。

首先,您必须确保端点通过 POST 接受数据,否则即使您正确发送数据也会失败,其次,如果您想将数据作为 url 发送-encoded 形式,您需要将 contentType 更改为 application/x-www-form-urlencoded 并将主体作为 url 编码的字符串或使用 FormData 对象(如果它在你的框架),例如:

var myData = new FormData();
myData.append("payload", encodeURI(PAYLOAD));

client.request({
  url: 'http://www.somewhere.com/integration',
  type: 'POST',
  contentType: 'application/x-www-form-urlencoded',
  headers: {
    apiKey: 'company',
    apiToken: '123'
  },
  dataType: 'xml',
  data: myData
}).then(
  function(data) {
    console.log(data);
  }
);

别忘了对有效载荷的内容进行编码。如果您的端点只接受 xml 编码的字符串,那么您必须按原样发送字符串,只需确保指定正确的 contentType,在这种情况下将是 application/xmltext/xml.

已解决。这是我必须做的(谢谢):

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);
  }
);

有用的文章: