Postman POST call works, but the same AJAX code does not work in JavaScript

David Peregrim April 8, 2020

I am using "/rest/api/content/22157686/child/attachment" call to upload an attachment to a Confluence space. When I try this in Postman, the file gets uploaded with no problem. I then tried to write JavaScript code to mimic that call. I used REST request. I could not get that to work even though several other of the Confluence API calls do work, including update a page. So I know the JavaScript is working and set up properly for the other API calls. For the create attachment call though, it seemed like the multipart/form-data was not being properly parsed and sent to the server. To simplify, I tried using AJAX instead of REST and copying the exact code from Postman. After some small modifications with headers, the call seems to be hitting the server, but the response is always null. Here is, more or less, the entire code. It is not long or complicated:

var FormData = require('form-data');
var form = new FormData();
form.append('file', 'C:/Users/<userid>/barnum-2.0/swagger.json');

settings = {
  'async': true,
  'crossDomain': true,
  'url': `https://share-staging.<company>.com/rest/api/content/22157686/child/attachment`,
  'method': 'POST',
  'dataType': 'json',
  'headers': {
  'X-Atlassian-Token': 'nocheck',
  'Cache-Control': 'no-cache',
  'Authorization': authorizationData,
  'X-Content-Type-Options': 'nosniff',
  'Accept': 'application/json; charset=utf-8'
  },
  'processData': false,
  'contentType': false,
  'mimeType': 'multipart/form-data',
  'multipart': true,
  'formData': form
}

   ajax(settings, function (response) {
      console.log('response :', response)
      done();
   });

1 answer

0 votes
Alex K
Atlassian Team
Atlassian Team members are employees working across the company in a wide variety of roles.
January 20, 2021

Hi David,

Thanks so much for your question.

It doesn't look like you are sending the file data, rather, you are sending a string of the file path. The correct way to send the file is by using a read stream (for example fs.createReadStream()). You can see this in the "form-data" npm library readme here: https://www.npmjs.com/package/form-data

Furthermore, if the server response is null then that could indicate an authentication issue. We also recommend monitoring the Confluence logs when sending the request to see if there are any obvious exceptions that indicate invalid request formatting. 

Thank you,
Alex K (Developer at Atlassian)

Confluence Data Center team

Suggest an answer

Log in or Sign up to answer
TAGS
AUG Leaders

Atlassian Community Events